Greedy、Reluctant、Possessive的区别
实例说话
看上面的表格我们发现这三种数量词的含意都相同(如X?、X??、X?+都表示一次或一次也没有),但他们之间还是有一些细微的区别的。我们先来看一个例子:
1.Greedy
public 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.Reluctant
public 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.Possessive
public 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数量词被称为“贪婪的”是因为匹配器被强制要求第一次尝试匹配时读入整个输入串,如果第一次尝试匹配失败,则从后往前逐个字符地回退并尝试再次匹配,直到匹配成功或没有字符可回退。
模式串:.*foo
查找串:xfooxxxxxxfoo
结果:matched form 0 to 13
其比较过程如下
Reluctant采用与Greedy相反的方法,它从输入串的首(字符)位置开始,在一次尝试匹配查找中只勉强地读一个字符,直到尝试完整个字符串。
模式串:.*foo
查找串:xfooxxxxxxfoo
结果:matched form 0 to 4
matched form 4 to 13
其比较过程如下
Possessive数量词总是读入整个输入串,尝试一次(仅且一次)匹配成功,不像Greedy,Possessive从不回退,即便这样做也可能使整体匹配成功。
模式串:.*foo
查找串:xfooxxxxxxfoo
结果:
//未匹配成功
其比较过程如下
参考文章:http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
再来看看几个例子:
模式串:.+[0-9]
查找串:abcd5aabb6
结果:matched form 0 to 10
模式串:.+?[0-9]
查找串:abcd5aabb6
结果:matched form 0 to 4
模式串:.{1,9}+[0-9]
查找串:abcd5aabb6
结果:matched form 0 to 10
模式串:.{1,10}+[0-9]
查找串:abcd5aabb6
结果:匹配失败

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Dreamweaver Mac版
视觉化网页开发工具