gpt4 book ai didi

java - 正则表达式模式帮助 java/groovy

转载 作者:行者123 更新时间:2023-12-05 00:13:27 31 4
gpt4 key购买 nike

我正在尝试解析这样的东西: ojit_代码

进入 Key1=[val123, val456], Key2=[val78, val123]一个概率是键和值都可以有非字母数字字符,比如 Map<String, List<String>>

这看起来像是我应该能够使用正则表达式模式匹配/分组来完成无需解析的简短工作,但我没有任何运气让正则表达式工作。任何正则表达式专家?

最佳答案

尝试

([^=\s]+)\s*=\s*\[\s*([^\s,]+),\s*([^\s,]+)\s*\]

这将匹配一个键/值对并提取反向引用 1 中的键、反向引用 2 中的第一个值和反向引用 3 中的第二个值。

在 Java 中,这看起来像这样:

Pattern regex = Pattern.compile("([^=\\s]+)\\s*=\\s*\\[\\s*([^\\s,]+),\\s*([^\\s,]+)\\s*\\]");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
key = regexMatcher.group(1);
val1 = regexMatcher.group(2);
val2 = regexMatcher.group(3);
}

解释:

([^=\s]+)   # Match one or more characters except whitespace or =
\s*=\s* # Match =, optionally surrounded by whitespace
\[\s* # Match [ plus optional whitespace
([^\s,]+) # Match anything except spaces or commas
,\s* # Match a comma plus optional whitespace
([^\s,]+) # Match anything except spaces or commas
\s*\] # Match optional whitespace and ]

关于java - 正则表达式模式帮助 java/groovy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203588/

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