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?
3 Answers
Reset to default 6You 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
版权声明:本文标题:javascript - Regular Expression Pattern Matching order - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744208643a2595313.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论