regex 为什么我的replace正则表达式不能给出给予正确的结果?

x6yk4ghg  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(98)

我有这个cmd输出,我在我的VB.NET应用程序中用作字符串输入:

output1: unshared
owner: unknown
public: EU
scope: this
value type: string
enum values: "----- / ASIL C", "SIL 0 / QM", "SIL 1 / ASIL A", "SIL 2 / ASIL B", "SIL 3 / ASIL D"

我试图实现的是从枚举值中获取数据,摆脱特殊的符号和空格(不包括,符号),并从中创建一个字符串数组。因此,输出字符串应该如下所示
"ASILC","SIL0QM","SIL1ASILA","SIL2ASILB","SIL3ASILD"
但是替换符号的正则表达式真的让我很困扰。
我的代码:

Sub Main()
        Dim values As String = "CMD OUTPUT"

        Dim pattern As String = "enum values:\s*(.*)" 'finding the right data line
        Dim match As Match = Regex.Match(values, pattern)
        Dim retVal As String() = New String() {}
        Dim locVal As String = " "

        If match.Success Then
            Dim capturedContent As String = match.Groups(1).Value
            locVal = Regex.Replace(capturedContent, """(.+?)""\s*(,|$)\s*", "$1$2") 'getting rid of special symbols/spaces
            Dim names As String() = locVal.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
            retVal = names
        End If
    End Sub

任何帮助/建议将不胜感激!

31moq8wy

31moq8wy1#

以下是我的建议如何解决它:
1.像你这样把整条线都拿来
1.以逗号分隔行以获得单独的值
1.在循环中,从每个值中剥离特殊字符并添加到retVal
代码可能有点错误,但它给出了这个想法,并有一些更多的解释:

Sub Main()
    Dim values As String = "CMD OUTPUT"

    Dim pattern As String = "enum values:\s*(.+)" 'finding the right data line
    Dim match As Match = Regex.Match(values, pattern)
    Dim retVal As String() = New String() {}
    Dim locVal As String = " "

    If match.Success Then
        Dim capturedContent As String = match.Groups(1).Value
        locVal = capturedContent.Split(',') 'split by comma
        
        For Each enumVal In locVal
            ' \W is non-word character, which will match all special chars at once
            ' It's enough to replace it with empty string.
            Dim finalValue = Regex.Replace(enumVal, "\\W", "")
            ' add finalValue to retVal
            
        Next enumVal
        
        retVal = names
    End If
End Sub

相关问题