我想知道这两个正则表达式是否有区别:
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/