简体   繁体   English

为什么此正则表达式在javascript中匹配?

[英]Why does this regex match in javascript?

Fiddle at http://jsfiddle.net/42zcL/ http://jsfiddle.net/42zcL/上提琴

I have the following code, which should alert "No Match". 我有以下代码,应提醒“ No Match”。 If I put the regex into regexpal.com and run it, it doesn't match (as expected). 如果我将正则表达式放入regexpal.com并运行它,则它与预期的不匹配。 With this code, it does match. 使用此代码,它确实匹配。 I know there is another way to do it, which works correctly - /^((.*)Waiting(.*))?$/ , but I am curious as to why this one fails. 我知道还有另一种方法可以正常工作-/ /^((.*)Waiting(.*))?$/ ((.*) /^((.*)Waiting(.*))?$/ ,但是我很好奇为什么这失败了。 It should match a string with the text "Waiting" in it or nothing at all. 它应该匹配一个带有文本“ Waiting”的字符串,或者完全不匹配。

var teststring="Anything";
if (teststring.match(/^((.*)Waiting(.*))|()$/)) alert('match');
else alert('No Match');

EDIT: Clearer example: 编辑:更清晰的例子:

var teststring="b";
if (teststring.match(/^(a)|()$/)) alert('match');
else alert('No Match');

Produces a Match, when I would expect "No Match" 当我期望“没有匹配”时,产生一个匹配

Expected behaviour, as per regexpal.com: 根据regexpal.com的预期行为:

teststring: a = match
teststring: b = no match

Actual behaviour in javascript: JavaScript中的实际行为:

teststring: a = match
teststring: b = match

Because you have |()$ at the end which is like saying "Match what comes before | but if you don't find it, match anything as long as there's an end of line." 因为结尾处有|()$ ,就像说“匹配之前的内容|但如果找不到它,则只要有行尾就匹配任何东西。”

- Full RegEx reference - 完整的RegEx参考

- Try it out - 试试看

Hopefully this explains it a little better: 希望这可以更好地解释它:

  1. The use of () in RegEx does not mean " Don't match anything ". 在RegEx 使用() 并不意味着“ 不匹配任何内容 ”。 If no characters are specified it will still match against () at each position in the string (letter position that is). 如果未指定任何字符,它将仍然与字符串中每个位置(即字母位置)的()匹配。 Imagine it like this: The word "Anything" turned into an array - [A,n,y,t,h,i,n,g] - if n = length of that array , the placeholder at [n] is non-empty , resulting in a "match" since no specific restriction was expressed in the pattern. 想象这样的:这个词“任何”变成数组- [A,N,Y,T,H,I,N,G] -如果n = length of that array ,在占位符[n] 是非空 ,导致“匹配”,因为在模式中未表达特定限制。
  2. Since #1 essentially means |()$ will return a positive result on any word tested , you will always see "match" in your alert. 由于#1本质上意味着|()$将对测试的任何单词返回肯定结果 ,因此您始终会在警报中看到“匹配”。

I'm pretty terrible at conveying my thoughts so maybe this previous stack answer will fill in whatever holes my answer left open. 我非常难以传达自己的想法,因此也许以前的堆栈答案会填补我的答案所留下的空白。

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

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