Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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_Capture Group - Fatal编程技术网

java正则表达式-捕获重复组

java正则表达式-捕获重复组,java,regex,capture-group,Java,Regex,Capture Group,我正在使用Java的正则表达式库。我想根据以下格式验证字符串: 31,5,46,7,86(...) 数字的数量不得而知。我想确保该字符串中至少有一个数字,并且每两个数字之间用逗号分隔。我还想从字符串中获取数字 (注意:这只是一个简化的示例,string.split无法解决我的实际问题) 我编写了以下正则表达式: ({[0-9]++)((?:,[0-9]++)*+) 验证部分工作正常。但是,当我尝试提取数字时,我得到了两组: Group1: 31 Group2: ,5,46,7,86 reg

我正在使用Java的正则表达式库。我想根据以下格式验证字符串:

31,5,46,7,86(...)
数字的数量不得而知。我想确保该字符串中至少有一个数字,并且每两个数字之间用逗号分隔。我还想从字符串中获取数字

注意:这只是一个简化的示例,string.split无法解决我的实际问题)

我编写了以下正则表达式:

({[0-9]++)((?:,[0-9]++)*+)
验证部分工作正常。但是,当我尝试提取数字时,我得到了两组:

Group1: 31
Group2: ,5,46,7,86
regex101版本:

有没有办法让我分别得到每个号码?i、 e.以收集结束:

[31, 5, 46, 7, 86]

提前感谢。

这可能适合您:

/(?=[0-9,]+$)((?<=,|^)[0-9]{1,2})(?=,|$)/g

/(?=[0-9,]+$)((?Java不允许您访问重复捕获组的单个匹配项。有关更多信息,请查看此问题:

Tim Pietzcker提供的代码也可以帮助您。如果您对其稍加修改,并为第一个数字添加一个特例,您可以使用以下代码:

String target = "31,5,46,7,86";

Pattern compileFirst = Pattern.compile("(?<number>[0-9]+)(,([0-9])+)*");
Pattern compileFollowing = Pattern.compile(",(?<number>[0-9]+)");

Matcher matcherFirst = compileFirst.matcher(target);
Matcher matcherFollowing = compileFollowing.matcher(target);

System.out.println("matches: " + matcherFirst.matches());
System.out.println("first: " + matcherFirst.group("number"));

int start = 0;
while (matcherFollowing.find(start)) {
    String group = matcherFollowing.group("number");

    System.out.println("following: " + start + " - " + group);
    start = matcherFollowing.end();
}

你能递归地得到它吗?现在捕获是有效的,但是验证不是:我试图在中间添加一个字母,而不是“不匹配”。你的建议是我最接近的,但是,有什么想法来调整它吗?@ ReMiLLO我更新了正则表达式,但是你想要的是不可能放入一个PCRE正则表达式,因为动态冷。不支持th LookBehind。我不知道Java使用的是什么regex flavor。但是,您的验证regex可能是这样的:
/^[0-9,]+$/
matches: true
first: 31
following: 0 - 5
following: 4 - 46
following: 7 - 7
following: 9 - 86