Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用正则表达式的Java中,如何从长度未知的字符串中捕获数字?_Java_Regex_Expression_Grouping_Capture - Fatal编程技术网

在使用正则表达式的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
锚捕获逗号后的连续数字

图案

解释

  • (?:
    非捕获组
  • \w+
    匹配1+个单词字符 -
    |
    • \G(?!^)
      在上一次匹配结束时而不是开始时断言位置
  • 关闭非捕获组
  • \h*,\h*
    在水平空白字符之间匹配逗号
  • ([0-9]+)
    捕获组1,匹配1+个数字
|

在带有双转义反斜杠的Java中:

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