简体   繁体   English

为什么正则表达式中的*。*返回undefined

[英]Why does *.* in regex return undefined

At least, in Javascript, tested on both Chrome and Node.js: 至少,在Javascript中,在Chrome和Node.js上进行了测试:

new RegExp(/foo(optional)*boo/).exec('foooptionalboo')

Will match the optional in parentheses: 将匹配括号中的optional

[ 'foooptionalboo',
'optional',
index: 0,
input: 'foooptionalboo' ]

But if you want there to be something in between the optional : 但是如果你想在可optional之间存在某些东西:

new RegExp(/foo.*(optional)*.*boo/).exec('foooptionalboo')

Then the optional is not found: 然后找不到optional

[ 'foooptionalboo',
'optional',
index: 0,
input: 'foooptionalboo' ]

Why is this? 为什么是这样?

The .* matches optional before (optional)* has a chance to. .*匹配optional之前(optional)*有机会。

Make it non-greedy (with a ? ) so it won't match if the thing following it will. 让它非贪婪(有一个? )所以如果跟随它的东西将不匹配。

/foo.*?(optional)*.*boo/.exec("foooptionalboo")

The problem with Quentin's answer is that .*? 昆汀回答的问题是.*? followed with an optional greedy subpattern (optional)? 接下来是一个可选的贪婪子模式(optional)? and a greedy dot matching pattern .* works in such a way that the .*? 一个贪婪的点匹配模式.*以这样的方式工作.*? only matches the empty string, and .* takes up the whole rest of the string. 只匹配空字符串,而.*占用字符串的其余部分。

Why does it happen? 为什么会这样? Because lazy subpatterns that can match an empty string (and it will always match here since it can match an empty string) work so: once the lazy subpattern matches, other subpatterns to the right are tried, and if a match is found, the lazy subpattern is not re-tried. 因为可以匹配空字符串的懒惰子模式(并且它将始终匹配,因为它可以匹配空字符串),所以:一旦lazy子模式匹配,尝试右边的其他子模式,如果找到匹配,则懒惰子模式不会重新尝试。 在此输入图像描述

To really grab an optional part, either use a specific pattern where no .* appears after the optional part, or (to make it more generic) use a tempered greedy token : 要真正获取可选部分,可以使用特定模式,其中在可选部分后面显示no .* ,或者(为了使其更通用)使用淬火贪婪令牌

foo(?:(?!optional).)*(optional)*.*boo
   ^^^^^^^^^^^^^^^^^^

See the regex demo 请参阅正则表达式演示

The (?:(?!optional).)* is the tempered greedy token that matches any text up to the first optional substring. (?:(?!optional).)*是调和的贪婪令牌,匹配任何文本到第一个optional子字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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