Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain Possessive Quantifiers to me? (Regular Expressions)

Tags:

regex

pcre

I am reading the PCRE doc, and it refers to possessive quantifiers, but does not explicitly or specifically define them. I know what a greedy quantifier is, and I know what a lazy quantifer is. But possessive?

The PCRE man page seems to be cheating when it uses the term without defining it. The man page specifically states that the term possessive quantifiers was first defined in Friedl's book. Well, that's great, but I don't have Friedl's book, and in reading the man page, between the lines, I cannot figure out what distinguishes possessive quantifiers from greedy ones.

  • ? = zero or one, greedy
  • ?? = zero or one, lazy
  • ?+ = zero or one, possessive
  • '+' = one or more, greedy
  • +? = one or more, lazy
  • ++ = one or more, possessive
like image 806
Cheeso Avatar asked Jul 13 '09 01:07

Cheeso


People also ask

What is possessive quantifier regex?

An quantifier in a regular expression may be greedy (the default), reluctant, or possesive. A possesive quantifier does this: The match starts with the first unmatched character in the string. The possessive quantifier starts matching from left to right one character at a time.

What are possessive quantifiers?

A possessive quantifier is similar to greedy quantifier. It indicates the engine to start by checking the entire string.It is different in the sense if it doesn't work, if match failed and there is no looking back. Following are various examples of Possessive Quantifiers using regular expression in java.

What is a lazy quantifier in regex?

A lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match. Because greediness and laziness change the order in which permutations are tried, they can change the overall regex match.


1 Answers

Perhaps the best place to start is Regex Tutorial - Possessive Quantifiers:

When discussing the repetition operators or quantifiers, I explained the difference between greedy and lazy repetition. Greediness and laziness determine the order in which the regex engine tries the possible permutations of the regex pattern. A greedy quantifier will first try to repeat the token as many times as possible, and gradually give up matches as the engine backtracks to find an overall match. A lazy quantifier will first repeat the token as few times as required, and gradually expand the match as the engine backtracks through the regex to find an overall match.


Possessive quantifiers are a way to prevent the regex engine from trying all permutations. This is primarily useful for performance reasons. You can also use possessive quantifiers to eliminate certain matches.

like image 156
Andrew Hare Avatar answered Sep 29 '22 11:09

Andrew Hare