VB.NET中Regex替换正则未获正确结果的问题求助
问题描述
我在VB.NET应用中将以下cmd输出作为字符串输入:
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"想要提取enum values中的数据,去除特殊符号和空格(逗号除外)并转换为字符串数组,预期输出格式为:
"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
解决方案
你的问题在于当前正则仅处理了引号和逗号周围的空格,未移除枚举项内部的空格、斜杠、连字符等多余符号。可以分两步处理:先提取每个枚举项,再逐个清理字符。
修改后的代码如下:
Imports System.Text.RegularExpressions Sub Main() Dim values As String = "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""" ' 匹配enum values行的内容 Dim enumPattern As String = "enum values:\s*(.*)" Dim match As Match = Regex.Match(values, enumPattern) Dim retVal As String() = New String() {} If match.Success Then Dim capturedContent As String = match.Groups(1).Value ' 提取每个被双引号包裹的枚举项 Dim itemPattern As String = """([^""]+)""" Dim itemMatches As MatchCollection = Regex.Matches(capturedContent, itemPattern) ' 逐个清理枚举项中的多余字符 Dim cleanedItems As New List(Of String)() For Each itemMatch As Match In itemMatches Dim originalItem As String = itemMatch.Groups(1).Value ' 移除所有非字母数字的字符(空格、斜杠、连字符等) Dim cleanedItem As String = Regex.Replace(originalItem, "[^A-Za-z0-9]", "") cleanedItems.Add(cleanedItem) Next retVal = cleanedItems.ToArray() ' 可选:验证输出格式 Console.WriteLine("""" & String.Join(""",""", retVal) & """") End If End Sub
代码说明
- 提取枚举项:使用
"""([^""]+)"""正则精准匹配每个双引号包裹的内容,确保不会遗漏或误捕获 - 清理字符:通过
[^A-Za-z0-9]匹配所有非字母数字的符号,替换为空字符串,彻底移除空格、/、-等多余内容 - 转换数组:将清理后的项存入列表再转为字符串数组,完全符合需求
运行后得到的数组内容为:{"ASILC", "SIL0QM", "SIL1ASILA", "SIL2ASILB", "SIL3ASILD"},与预期输出一致。
内容的提问来源于stack exchange,提问作者OxyK
相关产品推荐
相关产品推荐

