dangerChihuahua007
dangerChihuahua007

Reputation: 20915

Why does this regular expression match as few characters as possible?

I can match an 'a' followed by at least 2 other characters before another 'a' with the following regular expression.

a.{2,}?a

Interestingly, including the question mark makes the regex match the instance with the fewest number of middle characters possible, so for instance, given the following string,

abbabbbba

the regex will match the leftmost abba instead of the whole string. Why does including the question mark cause the regex to match the instance with the fewest number of middle characters?

Upvotes: 4

Views: 1015

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89564

The question mark after a quantifier makes the quantifier lazy. It is a basic feature of regex, you need to learn more about it.

a link: regular-expressions.info

(?:or|and) the one in hwnd comment.

Upvotes: 1

pushpraj
pushpraj

Reputation: 13679

? implies a lazy match

here is the details of your regex

/a.{2,}?a/

a matches the character a literally (case sensitive)

. matches any character (except newline)

{2,} Quantifier: Between 2 and unlimited times

? as few times as possible, expanding as needed [lazy]

a matches the character a literally (case sensitive)

Upvotes: 1

Related Questions