// *、+ 为贪婪模式,最大限度的匹配
public class Test001 {
public static void main(String[] args) throws Exception {
String text = "John writes about this, and John Doe writes about that, and John Wayne writes about everything.";
// *、+ 为贪婪模式,最大限度的匹配
Pattern pattern = Pattern.compile("(John)(.+) ");
Matcher matcher = pattern.matcher(text);
while(matcher.find()){
System.out.println(matcher.group(1)+matcher.group(2));
}
}
}
在 *、+ 或 ? 限定符之后放置 ?,该表达式从"贪心"表达式转换为"非贪心"表达式或者最小匹配。
public class Test001 {
public static void main(String[] args) throws Exception {
String text = "John writes about this, and John Doe writes about that, and John Wayne writes about everything.";
//在 *、+ 或 ? 限定符之后放置 ?,该表达式从"贪心"表达式转换为"非贪心"表达式或者最小匹配。
Pattern pattern = Pattern.compile("(John)(.+?) ");
Matcher matcher = pattern.matcher(text);
while(matcher.find()){
System.out.println(matcher.group(1)+matcher.group(2));
}
}
}

正则表达式的贪心与非贪心匹配
本文深入探讨了正则表达式中贪心与非贪心模式的区别,通过具体示例展示了如何使用Java中的Pattern和Matcher类来实现这两种匹配方式,帮助读者理解并掌握正则表达式的不同匹配行为。
791

被折叠的 条评论
为什么被折叠?



