I am kinda new to this Regex thing.
When analyzing some code I frequently e across the pattern .+?
or (.+?)
I can't seem to find the meaning of this pattern using my noobish deductive reasoning.
I am kinda new to this Regex thing.
When analyzing some code I frequently e across the pattern .+?
or (.+?)
I can't seem to find the meaning of this pattern using my noobish deductive reasoning.
Share Improve this question edited Jul 9, 2011 at 6:41 Brad Mace 27.9k18 gold badges109 silver badges152 bronze badges asked Mar 15, 2010 at 23:08 Dennis DDennis D 1,3434 gold badges17 silver badges24 bronze badges 1- regular-expressions.info/repeat.html explains it quite well – user187291 Commented Mar 15, 2010 at 23:16
2 Answers
Reset to default 13.
means any character (except a new line). +
means one or more. ?
in this context mean lazy or non-greedy. That means it will try to match the absolute minimum of characters that satisfy the quantifier. Example:
> 'abc'.match(/.+/)
["abc"]
> 'abc'.match(/.+?/)
["a"]
> 'abc'.match(/.*/)
["abc"]
> 'abc'.match(/.*?/)
[""]
It depends what kind of knowledge you have about patterns. Here's an explanation that assumes you have some kind of basic idea about what regular expressions are:
.
matches any character+
means repeat the last pattern 1 or more times- so far,
.+
means one or more characters ?
means ungreedy, which means the matching will stop with the first occasion.
A quick explanation on greediness:
/.+X/.exec("aaaXaaaXaaa");
["aaaXaaaX"]
/.+?X/.exec("aaaXaaaXaaa");
["aaaX"]
As you can see, the ?
character makes the search ungreedy, thus matching as little as possible.