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
非捕获组regex在Java中不起作用_Java_Regex - Fatal编程技术网

非捕获组regex在Java中不起作用

非捕获组regex在Java中不起作用,java,regex,Java,Regex,在线正则表达式测试表明,非标题组被忽略,但从java代码来看,它并没有被忽略 import java.util.*; import java.lang.*; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; class Ideone { public static void main (String[] args) throws java.lang.Exception

在线正则表达式测试表明,非标题组被忽略,但从java代码来看,它并没有被忽略

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Pattern PATTERN = Pattern.compile("(?:execute: ID: \\[\\s)([0-9]*)(?:\\s\\])");
        Matcher matcher = PATTERN.matcher("controllers.pring execute: ID: [ 290825814 ] executing bean: [ strong ]");
        if (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}
输出

execute: ID: [ 290825814 ]
期望

290825814

这是错误的假设,因为
matcher.group(0)
总是通过最新的
find
匹配方法返回匹配的全文

要获得
290825814
,必须使用:

Pattern PATTERN = Pattern.compile("(?:execute: ID: \\[\\s)([0-9]*)(?:\\s\\])");
Matcher matcher = PATTERN.matcher("controllers.pring execute: ID: [ 290825814 ] executing bean: [ strong ]");
if (matcher.find()) {
    System.out.println(matcher.group(1)); // 290825814
}
从:

捕获组从左到右索引,从一开始。组0表示整个模式,因此表达式m.Group(0)等价于m.Group()


因为您使用的是组0,所以捕获的是整个模式,与未捕获的组相同。我不知道为什么要将整个图案包装在非捕获组中。

该死!我怎么看不出来:)谢谢@anubhavaThanks,很快。通常,SOF在夜间处于活动状态:)如果仍被捕获,则使用非捕获组有什么意义?在您的示例中,使组0和2捕获将产生相同的结果?在执行正则表达式和保留其他组号时,应避免不必要的组以节省内存。