为什么我的替换正则表达式没有给出正确的结果?

Why does my replace regex does not give the right outcome?

提问人:OxyK 提问时间:10/11/2023 最后编辑:Michał TurczynOxyK 更新时间:10/11/2023 访问量:61

问:

我有这个 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

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

正则表达式 vb.net

评论

0赞 Wiktor Stribiżew 10/11/2023
也许是像 ideone.com/zs34qR 一样的东西?
0赞 OxyK 10/11/2023
@WiktorStribiżew效果很好,但输出值不是字符串数组:(

答:

0赞 Michał Turczyn 10/11/2023 #1

这是我的建议,你可以如何解决它:

  1. 像你一样获得整条生产线
  2. 拆分逗号上的行以获得单独的值
  3. 在一个循环中,从每个值中剥离特殊字符并添加到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