您的位置:首页 > 其它

正则表达式之贪婪模式讲解

2018-01-17 15:00 204 查看
没有注意过 贪婪模式和 非贪婪模式的含义

查看 这篇文章

参考 https://stackoverflow.com/questions/5319840/greedy-vs-reluctant-vs-possessive-quantifiers

关于正则表达式入门参考正则表达式30分钟入门教程

摘抄

A greedy quantifier first matches as much as possible. So the .* matches the entire string. Then the matcher tries to match the f following, but there are no characters left. So it “backtracks”, making the greedy quantifier match one less thing (leaving the “o” at the end of the string unmatched). That still doesn’t match the f in the regex, so it “backtracks” one more step, making the greedy quantifier match one less thing again (leaving the “oo” at the end of the string unmatched). That still doesn’t match the f in the regex, so it backtracks one more step (leaving the “foo” at the end of the string unmatched). Now, the matcher finally matches the f in the regex, and the o and the next o are matched too. Success!

A reluctant or “non-greedy” quantifier first matches as little as possible. So the .* matches nothing at first, leaving the entire string unmatched. Then the matcher tries to match the f following, but the unmatched portion of the string starts with “x” so that doesn’t work. So the matcher backtracks, making the non-greedy quantifier match one more thing (now it matches the “x”, leaving “fooxxxxxxfoo” unmatched). Then it tries to match the f, which succeeds, and the o and the next o in the regex match too. Success!

In your example, it then starts the process over with the remaining unmatched portion of the string, following the same process.

A possessive (占有)quantifier is just like the greedy quantifier, but it doesn’t backtrack. So it starts out with .* matching the entire string, leaving nothing unmatched. Then there is nothing left for it to match with the f in the regex. Since the possessive quantifier doesn’t backtrack, the match fails there.

+占有量词类似于greedy 模式,但是他不会往回走 .+ 中. 匹配了整个String

图形显示



总结:

* 贪婪模式 现将所有的字符串吞下 看是否匹配 如果不匹配 突出一个字符 然后再比叫 以此往复 直到匹配到位置

?非贪婪模式 读取第一个字符 看看批不匹配 .?foo 批不匹配整个 .?foo 如果不匹配那么继续吞下一个字符 直到匹配到第一个能匹配的 然后 在这个基础上 继续匹配下去如果还能匹配就是第二个子串

+ 占有符 .+foo .+ 这个符号现将 整个字符串吞下去然后后面是不是foo 如果不是 结束 没有吐的过程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  正则表达式