我试图解析vb.net中的文件。该文件是Mikrotik RouterOS上CLI命令的输出。 该文件看起来像这样,其中\和行的末尾表示该行继续在
下面# jan/03/2017 12:46:35 by RouterOS 6.38
# software id = 3BQ2-2I1I
#
/queue simple
add dst=WAN max-limit=5M/20M name=Compartido01 priority=1/1 queue=\
wireless-default/wireless-default target="" total-priority=1
add max-limit=512k/2M name="6206101450 - Simone Walter (2M) (P13)" parent=\
Compartido01 target=190.211.88.1/32
add max-limit=350k/1M name=\
"6206130537 - Figueroa Viviana del Carmen (1M) (P14)" parent=Compartido01 \
target=190.211.88.24/32
我设法跳过了第4行,然后将它们折叠起来,看起来像这样
"add dst=WAN max-limit=5M/20M name=Compartido01 priority=1/1 queue=wireless-default/wireless-default target="" total-priority=1"
"add max-limit=512k/2M name="6206101450 - Simone Walter (2M) (P13)" parent=Compartido01 target=190.211.88.1/32"
"add max-limit=350k/1M name="6206130537 - Figueroa Viviana del Carmen (1M) (P14)" parent=Compartido01 target=190.211.88.24/32"
我需要做的是提取有关这些字符串的信息,例如" name = XXXXXX"和"目标= XXXXX" 我可以使用空格作为分隔符进行拆分,但是" name"字段可以在其中包含空格 任何人都可以给我一个提示吗?
答案 0 :(得分:1)
你需要的是一个RegEx匹配解析器......找到一个here。看看你能否从中获得所需的东西。
Imports System.Text.RegularExpressions
Module Parser
Public Function ParseKeyValuePairs(ByVal Buffer As String) As Dictionary(Of String, String)
Dim Result = New Dictionary(Of String, String)
'---- There are 3 sub patterns contained here, seperated at the | characters
' The first retrieves name="value", honoring doubled inner quotes
' The second retrieves name=value where value can't contain spaces
' The third retrieves name alone, where there is no "=value" part (ie a "flag" key
' where simply its existance has meaning
Dim Pattern = "(?:(?<key>[\w-]+)\s*\=\s*""(?<value>[^""]*(?:""""[^""]*)*)"") | " & _
"(?:(?<key>[\w-]+)\s*\=\s*(?<value>[^""\s]*)) | " & _
"(?:(?<key>[\w-]+)\s*)"
Dim r = New System.Text.RegularExpressions.Regex(Pattern, RegexOptions.IgnorePatternWhitespace)
'---- parse the matches
Dim m As System.Text.RegularExpressions.MatchCollection = r.Matches(Buffer)
'---- break the matches up into Key value pairs in the return dictionary
For Each Match As System.Text.RegularExpressions.Match In m
Result.Add(Match.Groups("key").Value, Match.Groups("value").Value)
Next
Return Result
End Function
Public Sub Main()
Dim s = "Key1=Value Key2=""My Value here"" Key3=Test Key4 Key5"
Dim r = ParseKeyValuePairs(s)
For Each i In r
Debug.Print(i.Key & "=" & i.Value)
Next
End Sub
End Module