What is the difference between `Greedy` and `Reluctant` regular expression quantifiers?

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"

Leave a Comment