Java正则表达中Greedy Reluctant Possessive 的区别
上1篇文章《编程思想之正则表达式 》中讲了正则表达式的原理、使用方法和常见的正则表达式总结,本文将进1步探讨Java正则表达中Greedy、Reluctant、Possessive3种策略的区分。 从Java的官方文档http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html中我们可以看到,正则表达式表示数量词的符号有3套,分别是Greedy(贪婪的)、Reluctant(委曲的)和Possessive(独占的)。其含义以下:
Greedy、Reluctant、Possessive的区分实例说话看上面的表格我们发现这3种数量词的含义都相同(如X?、X??、X?+都表示1次或1次也没有),但他们之间还是有1些细微的区分的。我们先来看1个例子: 1.Greedypublic static void testGreedy() {
Pattern p = Pattern.compile(".*foo");
String strText = "xfooxxxxxxfoo";
Matcher m = p.matcher(strText);
while (m.find()) {
System.out.println("matched form " + m.start() + " to " + m.end());
}
} 结果:matched form 0 to 13
2.Reluctantpublic static void testReluctant() {
Pattern p = Pattern.compile(".*?foo");
String strText = "xfooxxxxxxfoo";
Matcher m = p.matcher(strText);
while (m.find()) {
System.out.println("matched form " + m.start() + " to " + m.end());
}
} 结果:matched form 0 to 4 matched form 4 to 13
3.Possessivepublic static void testPossessive() {
Pattern p = Pattern.compile(".*+foo");
String strText = "xfooxxxxxxfoo";
Matcher m = p.matcher(strText);
while (m.find()) {
System.out.println("matched form " + m.start() + " to " + m.end());
}
} 结果:
//未匹配成功
原理讲授Greedy数量词被称为“贪婪的”是由于匹配器被强迫要求第1次尝试匹配时读入全部输入串,如果第1次尝试匹配失败,则从后往前逐一字符地回退并尝试再次匹配,直到匹配成功或没有字符可回退。 模式串:.*foo 查找串:xfooxxxxxxfoo 结果:matched form 0 to 13
其比较进程以下
模式串:.*foo 查找串:xfooxxxxxxfoo 结果:matched form 0 to 4 matched form 4 to 13
其比较进程以下
Possessive数量词总是读入全部输入串,尝试1次(仅且1次)匹配成功,不像Greedy,Possessive从不回退,即使这样做也可能使整体匹配成功。 模式串:.*foo 查找串:xfooxxxxxxfoo 结果: //未匹配成功
其比较进程以下
参考文章:http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
再来看看几个例子: 模式串:.+[0⑼] 查找串:abcd5aabb6 结果:matched form 0 to 10
模式串:.+?[0⑼] 查找串:abcd5aabb6 结果:matched form 0 to 4
模式串:.{1,9}+[0⑼] 查找串:abcd5aabb6 结果:matched form 0 to 10
模式串:.{1,10}+[0⑼] 查找串:abcd5aabb6 结果:匹配失败
如果您有甚么疑惑和想法,请在评论处给予反馈,您的反馈就是最好的测评师!由于本人技术和能力有限,如果本博文有毛病或不足的地方,敬请体谅并给出您宝贵的建议!
========================欢迎关注编程思想系列文章======================== 编程思想之正则表达式 编程思想之迭代器 编程思想之递归 编程思想之回调
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |