我的正则表达式如下所示:"[a-zA-Z]+[\t]*(?:,[\t]*(\\d+)[\t]*)*"
我可以用这个匹配线条,但我不知道如何捕获数字,我认为它必须与分组做一些事情。
例如:从字符串“asd , 5 ,2,6 ,8”
中,如何捕获数字5 2 6和8?
更多示例:
sdfs6df -> no capture
fdg4dfg, 5 -> capture 5
fhhh3 , 6,8 , 7 -> capture 6 8 and 7
asdasd1,4,2,7 -> capture 4 2 and 7
这样我就可以继续处理这些数字了。提前致谢。
最佳答案
您可以匹配前导单词字符并使用 \G
anchor 捕获逗号后的连续数字。
模式
(?:\w+|\G(?!^))\h*,\h*([0-9]+)
说明
(?:
非捕获组\w+
匹配 1 个以上单词字符 -|
或\G(?!^)
在上一场比赛结束时断言位置,而不是在开始时
)
关闭非捕获组\h*,\h*
匹配水平空白字符之间的逗号([0-9]+)
捕获组 1,匹配 1+ 位数字
在带有双转义反斜杠的 Java 中:
String regex = "(?:\\w+|\\G(?!^))\\h*,\\h*([0-9]+)";
示例代码
String regex = "(?:\\w+|\\G(?!^))\\h*,\\h*([0-9]+)";
String string = "sdfs6df -> no capture\n\n"
+ "fdg4dfg, 5 -> capture 5\n\n"
+ "fhhh3 , 6,8 , 7 -> capture 6 8 and 7\n\n"
+ "asdasd1,4,2,7 -> capture 4 2 and 7";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
输出
5
6
8
7
4
2
7
关于java - 在Java中使用正则表达式,如何从未知长度的字符串中捕获数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432785/