有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式中的java问号:模式之间的差异。编译(“\”标题\“:\”(*)\"");' 和'模式。编译(“\”标题\“:\”*\”);'

我想知道这两个正则表达式是否有区别:

Pattern.compile("\"title\":\"(.*?)\"");
Pattern.compile("\"title\":\".*\"");

部分(.*?).*看起来具有相同的含义

在这里,我得到了完全相同的结果:

        String title = null;
        Pattern p = Pattern.compile("\"title\":\"(.*?)\"");
        //Pattern p = Pattern.compile("\"title\":\".*\"");
        Matcher m = p.matcher("sdfssdfsdfsdfsdf\"title\":\"Here is the title\"sdfgdfgdfgdfgdfg");
        if (m.find()) {
            title = m.group();
        }
        System.out.println(title);

输出:

"title":"Here is the title"

如果我不使用括号,我仍然可以找到这样的单独组:

Pattern p = Pattern.compile("\"title\":\".*?\"");
Matcher m = p.matcher("sdfssdfsdfsdfsdf\"title\":\"Here is the title\"dfdfgrt\"title\":\"Here is the title\"");
while (m.find()) {
    System.out.println(m.group());
}

输出:

"title":"Here is the title"
"title":"Here is the title"

我真的需要括号吗


共 (1) 个答案

  1. # 1 楼答案

    这里有两件事:

    ()>;指定一个捕获组。因此,如果您想捕获某个并希望稍后引用它,可以使用(what you want to capture here)。没有大括号,就无法捕获数据

    .*>;是贪婪的,也就是说,它试图获取整个字符串,减少一个字符,然后再次尝试匹配

    .*?>;是惰性的(即,从长度0开始,尝试匹配字符串,并在第一次匹配时停止)

    你可以看看the official documentation here

    在没有capturing的情况下为matching尝试此代码

        Pattern p = Pattern.compile("abc(.*?)");
        Matcher m = p.matcher("abc");
        while (m.find()) {
            System.out.println("hi");
            System.out.println("group1: " +  m.group(1));
        }
    

    输出:

    hi
    group1: