gpt4 book ai didi

regex - 将字符串拆分为参数和值

转载 作者:行者123 更新时间:2023-12-04 05:17:55 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

关于regex - 将字符串拆分为参数和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14001923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com