What are the differences between lazy, greedy and possessive quantifiers?

爷,独闯天下 提交于 2019-11-30 15:14:30

Take the string

aaaab

and see how the following regexes match it:

Regex          Submatches
               group 1  group 2  group3
(a?)(a*)(ab)   a        aa       ab
(a??)(a*)(ab)           aaa      ab
(a?+)(a*)(ab)  a        aa       ab
(a*)(a?)(ab)   aaa               ab
(a*?)(a?)(ab)  aa       a        ab
(a*+)(a?)(ab)  aaaa              <Match fails!>
(a+)(a*)(ab)   aaa               ab 
(a+?)(a*)(ab)  a        aa       ab
(a++)(a*)(ab)  aaaa              <Match fails!>

Explanation:

  • a? tries to match one a, but it's prepared to match nothing if that's necessary for the whole match to succeed.
  • a?? tries to match nothing, but it's prepared to match one a if that's necessary for the whole match to succeed.
  • a?+ tries to match one a. If it can do that, it will not back down to match nothing if that were necessary for the overall match to succeed. If it can't match an a, then it will gladly match nothing, though.
  • a* tries to match as many as as it can, but it's prepared to match fewer as, even nothing if that's necessary for the whole match to succeed.
  • a*? tries to match nothing, but it's prepared to match just as many as as is absolutely necessary in order for the whole match to succeed, but not more.
  • a*+ tries to match as many as as it can. If it can do that, it will not back down to match fewer as if that were necessary for the overall match to succeed. If it can't match even a single a, then it will gladly match nothing, though.
  • a+ tries to match as many as as it can, but it's prepared to match fewer as (but at least one) if that's necessary for the whole match to succeed.
  • a+? tries to match only one a, but it's prepared to match just as many as as is absolutely necessary in order for the whole match to succeed, but not more.
  • a++ tries to match as many as as it can. If it can do that, it will not back down to match fewer as if that were necessary for the overall match to succeed. If it can't match even a single a, then the regex fails.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!