在使用正则表达式的Java中,如何从长度未知的字符串中捕获数字?
我的正则表达式如下所示:在使用正则表达式的Java中,如何从长度未知的字符串中捕获数字?,java,regex,expression,grouping,capture,Java,Regex,Expression,Grouping,Capture,我的正则表达式如下所示:“[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 -
“[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
锚捕获逗号后的连续数字
图案
解释
非捕获组(?:
匹配1+个单词字符 -\w+
或|
在上一次匹配结束时而不是开始时断言位置\G(?!^)
关闭非捕获组)
在水平空白字符之间匹配逗号\h*,\h*
捕获组1,匹配1+个数字([0-9]+)
String regex = "(?:\\w+|\\G(?!^))\\h*,\\h*([0-9]+)";
示例代码
输出
5
6
8
7
4
2
7
有什么限制吗?或者直接获取数字?只需在循环中使用
“\\d+”
和匹配器#find()
。看,所以不要在字符串的其余部分打扰你,\\d+@remmaks你是说像这样吗<代码>(?:\w+\G(?!^))\h*,\h*([0-9]+)@Thefourthbird是的,很好,谢谢。
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