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

标签 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 -> capture 4 2 and 7

这样我就可以继续处理这些数字了。提前致谢。

最佳答案

您可以匹配前导单词字符并使用 \G anchor 捕获逗号后的连续数字。

模式

(?:\w+|\G(?!^))\h*,\h*([0-9]+)

说明

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

Regex demo | Java demo

在带有双转义反斜杠的 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/

相关文章:

java - Stanford CoreNLP - 线程异常 "main"java.lang.OutOfMemoryError : Java heap space

regex - 在cocoa中解析URL

regex - 'lazy' 和 'greedy' 在正则表达式中意味着什么?

c# - 如何正确合并具有不同参数的 lambda 表达式

java - isDisplayed() 与 Selenium 中的 isVisible()

java - 从包含中重定向 JSP 中的用户 - java 语法错误

php - 正则表达式中的希伯来语特殊字符

javascript - 元素 :angular 2/4 的 html 中不可绑定(bind)的单大括号

java - 打印居中对齐的二维数组

java - 替换某些符号之间的文本