Sun*_*nny 2 java regex groovy parsing pattern-matching
我正在尝试解析这样的事情:
Key1=[val123, val456], Key2=[val78, val123]
进入Map<String, List<String>>
A问题是密钥和值都可能具有非字母num字符.:-_
这看起来像我应该能够使用正则表达式模式匹配/组事件来进行简短的工作而不进行解析,但我没有任何运气获得正则表达式表达式.任何regexp大师?
尝试
([^=\s]+)\s*=\s*\[\s*([^\s,]+),\s*([^\s,]+)\s*\]
Run Code Online (Sandbox Code Playgroud)
这将匹配一个键/值对并提取后向引用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);
}
Run Code Online (Sandbox Code Playgroud)
说明:
([^=\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 ]
Run Code Online (Sandbox Code Playgroud)