在使用正则表达式的Java中,如何从长度未知的字符串中捕获数字



我的正则表达式如下所示:"[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+|G(?!^))h*,h*([0-9]+)

解释

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

Regex演示| Java演示

在Java中使用双转义反斜杠:

String regex = "(?:\w+|\G(?!^))\h*,\h*([0-9]+)";

示例代码

String regex = "(?:\w+|\G(?!^))\h*,\h*([0-9]+)";
String string = "sdfs6df -> no capturenn"
+ "fdg4dfg, 5 -> capture 5nn"
+ "fhhh3      ,     6,8    , 7 -> capture 6 8 and 7nn"
+ "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

最新更新