From the Pattern
javadocs:
Greedy quantifiers: X? X, once or not at all X* X, zero or more times X+ X, one or more times X{n} X, exactly n times X{n,} X, at least n times X{n,m} X, at least n but not more than m times Reluctant quantifiers: X?? X, once or not at all X*? X, zero or more times X+? X, one or more times X{n}? X, exactly n times X{n,}? X, at least n times X{n,m}? X, at least n but not more than m times
The description of what they do is the same...so, what is the difference?
I would really appreciate some examples.
I am coding in Java, but I hear this concept is the same for most modern regex implementations.
A reluctant quantifier indicates the search engine to start with the shortest possible piece of the string. Once match found, the engine continue; otherwise it adds one character to the section of the string being checked and search that, and so on.
Greedy Quantifier (Default) Greedy quantifiers try to match the longest text that matches a given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the whole text doesn't match, remove the last character and try again, repeating the process until a match is found.
The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. By using a lazy quantifier, the expression tries the minimal match first.
By default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible.
A greedy operator always try to "grab" as much of the input as possible, while a reluctant quantifier will match as little of the input as possible and still create a match.
Example:
"The red fox jumped over the red fence" /(.*)red/ => \1 = "The red fox jumped over the " /(.*?)red/ => \1 = "The " "aaa" /a?a*/ => \1 = "a", \2 = "aa" /a??a*/ => \1 = "", \2 = "aaa" "Mr. Doe, John" /^(?:Mrs?.)?.*\b(.*)$/ => \1 = "John" /^(?:Mrs?.)?.*?\b(.*)$/ => \1 = "Doe, John"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With