I’m trying to learn some basic Javascript regex. As starters, I read the documentation and this SO question:
How do you access the matched groups in a JavaScript regular expression?
I think I’ve deciphered most of the expression:
/(?:^|\s)format_(.*?)(?:\s|$)/g
Except this part:
(.*?)
I know that
.*
is to match 0 or more occurrences of any character (except newline or line terminator).
But I can’t figure out why the
?
is needed.
I was playing with something similar:
/(?:^|\s)ab(.*?)ab(?:\s|$)/
' ab4545ab '
And things have been behaving the same with or without the
?
in
(.*?)
Any thoughts?
Thanks!
It makes the
.*non-greedy. This means that the first occurrence of the next valid character sequence in the regex will halt the.*.Without the
?, the.*will consume until the last occurrence of the next valid character sequence in the regex.So the greedy one consumes past the first “bar” to the last “bar”.
The non-greedy only goes to the first “bar”.