Practical use of possessive quantifiers regex

This question already has an answer here:

  • Greedy vs. Reluctant vs. Possessive Quantifiers 7 answers

  • There are many (regex dependent) implementation details so it's difficult to generalize these things. For example with ^.*.* you get a match on the string " " . With ^.*+.* you don't. Because the first matcher already swallowed the whole string of whitespace.

    You can use it in any case where you don't want the next part of your regex to accidentally match a part of the preceding.

    You can test this with PCRE settings at https://regex101.com/


    Note that if a possessive patter matches, then so will the greedy pattern. The converse is not true. Therefore you can use a possessive quantifier if you want to limit your matches to a smaller set.

    Secondly possessive quantifiers are useful when the input string does not match your pattern. Since they "eat" their input and don't backtrack they will be faster in detecting a non-match. In extreme cases this is called catastrophic backtracking and has brought down sites (including StackOverflow, see here).

    链接地址: http://www.djcxy.com/p/76908.html

    上一篇: 了解Python正则表达式贪婪修饰符

    下一篇: 所有格量化符正则表达式的实际使用