In the Regular Expression engines in all languages I'm familiar with, the .*
notation indicates matching zero or more characters. Consider the following Javascript code:
var s = "baaabcccb";
var pattern = new RegExp("b.*b");
var match = pattern.exec(s);
if (match) alert(match);
This outputs baaabcccb
The same thing happens with Python:
>>> import re
>>> s = "baaabcccb"
>>> m = re.search("b.*b", s)
>>> m.group(0)
'baaabcccb'
What is the reason that both of these languages match "baaabcccb"
instead of simply "baaab"
? The way I read the pattern b.*b
is "find a sub-string that starts with b
, then has any number of other characters, then ends with b
." Both baaab
and baaabcccb
satisfy this requirement, yet both Javascript and Python match the latter. I would have expected it to match baaab
, simply because that sub-string satisfies the requirement and appears first.
So why does the pattern match baaabcccb
in this case? And, is there any way to modify this behavior (in either language) so that it matches baaab
instead?
You can make the regex not greedy by adding a ?
after the *
like this: b.*?b
. Then it will match the smallest string posible. By default the regex is greedy and will try to find the longest possible match.
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