Reputation:
Can someone please illustrate it what is the difference between the following regular expressions?
/b\w+?/g
and
/b\w/g
based on the documentation of regexr for Lazy ?:Makes the preceding quantifier lazy, causing it to match as few characters as possible. By default, quantifiers are greedy, and will match as many characters as possible.
Upvotes: 3
Views: 2437
Reputation: 336228
Both regexes will match the same thing (one "alphanumeric" character). The difference between them becomes noticeable only when the regex becomes more complex.
For example,
\b\w\.
will match "A."
but not "Mr."
because \w
matches only one character.
\b\w+?\.
will match both. This hasn't yet to do with the laziness but with the lack of a quantifier in the first regex. But if you compare
\b\w+\d
and
\b\w+?\d
you'll notice an important difference: Both regexes will match the string "R2D2"
differently - the first one matches "R2D2"
, the second one only matches "R2"
because the ?
tells the \w+
token to match as few characters as possible, so it stops the match after R
(even though it could match more. It will only match more if the regex wouldn't match otherwise).
Upvotes: 4