2

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

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

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

编辑:请提供代码、正则表达式或类似的示例。

4

1 回答 1

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
于 2012-12-22T10:49:46.693 回答