Why is it that "hello".match(/^(.*?)?/)[0]
evaluates to "h"
rather than to ""
?
Put another way, why does following a lazy expression (.*?)
with a zero-or-one quantifier ?
make it a little greedy?
It's not that the inner quantifier has become greedy, but that it has tried to avoid matching a completely empty section. This is why the .*
still only matches the first character, not the whole word.
This is an oddity of JavaScript regex. Empty matching sections with greedy quantifiers on them are handled slightly differently to other common regex engines. The real reason for this is intricate. See: Greediness behaving differently in JavaScript?
A workaround is to make the outer quantifier lazy too, with an additional question mark:
"hello".match(/^(.*?)??/)[0] // output: ""
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