java中正则匹配贪婪模式和非贪婪模式实例
java中正则匹配贪婪模式和非贪婪模式实例
贪婪模式和非贪婪模式指的是在正则匹配过程中的行为。
-
贪婪模式:匹配最长的匹配值 非贪婪模式:匹配最短的匹配值
java中的Pattern支持贪婪和非贪婪模式,通过不同的表达式区分
贪婪模式表达式:
非贪婪模式表达式:
案例:
public class Regex{
public static void main(String[] args) {
//提取td元素里的内容
String str="<table><tr><td>hello world</td><td>hello regex</td></tr></table>";
//贪婪模式 * + {n,} 默认情况是贪婪模式匹配
System.out.println("贪婪模式");
//编译正则表达式到模式对象
Pattern p=Pattern.compile("<td>.*</td>");
//得到匹配器
Matcher m=p.matcher(str);
//通过find方法查找匹配,找到就返回true,否则返回false
while(m.find()){
//通过group方法获取前面find查找到的子字符串,start、end方法获取子字符串开始和结束位置
System.out.println(m.group()+" 位置:["+m.start()+","+m.end()+"]");
}
//非贪婪模式,?跟在 * + {n,} 等的后面时,表示非贪婪模式,注意和子表达式后面的?区分开,子表达式后的?表示匹配0次或1次
System.out.println("非贪婪模式");
p=Pattern.compile("<td>.*?</td>");
m=p.matcher(str);
while(m.find()){
System.out.println(m.group()+" 位置:["+m.start()+","+m.end()+"]");
}
}
}
运行结果:
贪婪模式
<td>hello world</td><td>hello regex</td> 位置:[11,51]
非贪婪模式
<td>hello world</td> 位置:[11,31]
<td>hello regex</td> 位置:[31,51]
