简体   繁体   中英

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?

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.

.* is a greedy match. .*? is the non-greedy version

Because * and also + are essentially greedy (at least in python, i am not sure about js). They will try to match as far as possible. if you want to avoid this issue you could add ? after them.

Here is a great tutorial about this, in the greedy vs non-greedy section: google python class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM