将字符串拆分为参数和值

时间:2012-12-22 10:12:08

标签: regex vb.net

我知道基本的分割字符串操作,但作为一个VB.NET初学者,我想知道是否存在一些方便的方法来分割带参数的字符串(令牌)。
字符串的大小和内容可能不同,但总是使用相同的模式“[parameter] - > value” 像这样:

[name] John [year]   1990 [gender]M[state] Washington[married] No[employed] No

如何解析这个语法错误的书写字符串以获取参数>值对?

编辑:代码,正则表达式或类似的例子。

1 个答案:

答案 0 :(得分:3)

您可以使用正则表达式执行此操作:

Dim RegexObj As New Regex( _
    "\[         # Match an opening bracket"                         & chr(10) & _
    "(?<name>   # Match and capture into group ""name"":"           & chr(10) & _
    " [^[\]]*   # any number of characters except brackets"         & chr(10) & _
    ")          # End of capturing group"                           & chr(10) & _
    "\]         # Match a closing bracket"                          & chr(10) & _
    "\s*        # Match optional whitespace"                        & chr(10) & _
    "(?<value>  # Match and capture into group ""value"":"          & chr(10) & _
    " [^[\]]*?  # any number of characters except brackets"         & chr(10) & _
    ")          # End of capturing group"                           & chr(10) & _
    "(?=        # Assert that we end this match either when"        & chr(10) & _
    " \s*\[     # optional whitespace and an opening bracket"       & chr(10) & _
    "|          # or"                                               & chr(10) & _
    " \s*$      # whitespace and the end of the string"             & chr(10) & _
    ")          # are present after the current position", _
    RegexOptions.IgnorePatternWhitespace)
Dim MatchResults As Match = RegexObj.Match(SubjectString)
While MatchResults.Success
    parameter = MatchResults.Groups("name").Value
    value = MatchResults.Groups("value").Value
    ' do something with the parameter/value pairs
    MatchResults = MatchResults.NextMatch()
End While