java regex – 捕获重复的组
我正在使用Java的正则表达式库。 我想根据以下格式validation字符串:
31,5,46,7,86(...)
数量不明。 我想确保该字符串中至少有一个数字,并且每两个数字用逗号分隔。 我也想从字符串中获取数字。
( 注意:这只是一个简化的例子,string.split不会解决我的实际问题)
我写了以下正则表达式:
({[0-9]++)((?:,[0-9]++)*+)
validation部分有效。 但是,当我尝试提取数字时,我得到2组:
Group1: 31 Group2: ,5,46,7,86
regex101版本: https ://regex101.com/r/xJ5oQ6/3
有没有办法可以分别得到每个号码? 即结束集合:
[31, 5, 46, 7, 86]
提前致谢。
Java不允许您访问重复捕获组的各个匹配项。 有关更多信息,请查看此问题: 正则表达式 – 捕获所有重复组
Tim Pietzcker提供的代码也可以为您提供帮助。 如果你稍微改写它并为第一个数字添加一个特殊情况,你可以使用这样的东西:
String target = "31,5,46,7,86"; Pattern compileFirst = Pattern.compile("(?[0-9]+)(,([0-9])+)*"); Pattern compileFollowing = Pattern.compile(",(? [0-9]+)"); Matcher matcherFirst = compileFirst.matcher(target); Matcher matcherFollowing = compileFollowing.matcher(target); System.out.println("matches: " + matcherFirst.matches()); System.out.println("first: " + matcherFirst.group("number")); int start = 0; while (matcherFollowing.find(start)) { String group = matcherFollowing.group("number"); System.out.println("following: " + start + " - " + group); start = matcherFollowing.end(); }
这输出:
matches: true first: 31 following: 0 - 5 following: 4 - 46 following: 7 - 7 following: 9 - 86
这可能对你有用:
/(?=[0-9,]+$)((?<=,|^)[0-9]{1,2})(?=,|$)/g
以上捕获一个或两个数字后跟或输入结束。
请注意,我使用了g
lobal修饰符。
在线尝试