admin管理员组

文章数量:1400128

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?

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?

Share Improve this question edited Jun 14, 2012 at 14:14 Channel72 asked Jun 14, 2012 at 3:36 Channel72Channel72 24.8k35 gold badges115 silver badges187 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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

本文标签: javascriptRegular Expression Pattern Matching orderStack Overflow