Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Pattern Matching order

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?

like image 220
Channel72 Avatar asked Dec 27 '22 23:12

Channel72


1 Answers

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.

like image 161
Trevor Avatar answered Jan 08 '23 11:01

Trevor