2017-01-05 140 views
0

我試圖解析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" 

我需要做的是提取這些字符串的信息,如「名稱= XXXXXX」和「目標= XXXXX」 我可以使用空格作爲分隔符分隔,但「名稱」字段可以有空格 任何人都可以給我一個提示 ?

回答

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