我有一个像这样的字符串:
[potato=carrot,test=12b,apple=peer,tree={oak=1,birch={value=3}},foo=bar]
我想使用 Java 正则表达式获得一个字符串数组:
potato=carrot
test=12b
apple="peer"
tree={oak=1,birch={value=3}}
foo=bar
我尝试了几种模式但没有结论...... 就是这样,所以如果有人有想法......:)
提前谢谢您!
最佳答案
你可以尝试这个正则表达式
原始:[^\[\],{}]+=(?:[^\[\],{}]+|(?=\{)(?:(?=.*?\{(?!.*?\1)(.*\}(?!.*\2).*))(?=.*?\}(?!.*?\2)(.*)) .)+?.*?(?=\1)[^{]*(?=\2$))
字符串:"[^\\[\\],{}]+=(?:[^\\[\\],{}]+|(?=\\{)(?: (?=.*?\\{(?!.*?\\1)(.*\\}(?!.*\\2).*))(?=.*?\\}(?! .*?\\2)(.*)).)+?.*?(?=\\1)[^{]*(?=\\2$))"
演示:http://java-regex-tester.appspot.com/regex/14b6e038-b683-44cd-b46e-c161b0cd9001
请注意,您可以将 [^\[\],{}]+
替换为 \w+
,您会得到相同的结果。
可读版本:
[^\[\],{}]+ =
(?:
[^\[\],{}]+
|
(?= \{ )
(?:
(?=
.*? \{
(?! .*? \1 )
( # (1 start)
.* \}
(?! .* \2 )
.*
) # (1 end)
)
(?=
.*? \}
(?! .*? \2 )
( .* ) # (2)
)
.
)+?
.*?
(?= \1 )
[^{]*
(?= \2 $ )
)
关于java - 分割字符串,忽略括号包围的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50309451/