java - 正则表达式中的问号 : difference between 'Pattern.compile("\"title\":\"(.*?)\"") ;' and ' Pattern. 编译 ("\"标题\":\".*\"");'

标签 java regex

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

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"

那么 - 我真的需要括号吗?

最佳答案

这里有两件事:

() --> 指定一个捕获组。因此,如果您想要捕获某些内容并希望稍后引用它,您可以使用(您想要在此处捕获的内容)。如果没有大括号,您就无法捕获数据。

.* --> 是贪婪的,即它尝试抓取整个字符串并少一个字符并尝试再次匹配。

.*? --> 是惰性的(又名不情愿),即从长度 0 开始并尝试匹配字符串并在第一个匹配处停止。

您可以查看the official documentation here .

尝试使用此代码进行匹配而不捕获

    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:

关于java - 正则表达式中的问号 : difference between 'Pattern.compile("\"title\":\"(.*?)\"") ;' and ' Pattern. 编译 ("\"标题\":\".*\"");',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29075066/

相关文章:

java - 为什么这个正则表达式没有给出预期的输出?

java - 使用 Rest High Level Client 检索数据或将数据插入 Elastic Search 时出现 SocketTimeoutException

java - 引用正则表达式中以前匹配的组

javascript - RegEx 只找到第一个值

java - 在 Java 中使用 Regex 确定字符串是否为 URL

c++ - lambda 中使用的静态变量未初始化

java - 如何在 IBatis2 中处理带有 In 子句和空 Java 列表的 SQL 语句?

java - 为什么我在 Java 8 中无法正确解析这个英文日期?

java - 用新的 Asynctask 替换 AsyncTask 时会发生什么

java - Fragments 中的 Android FATAL 异常