<html><body><script>
var matches = /(\w+)(\s*(\w+))?/.exec("aaa");
alert(matches.length);
alert(typeof(matches[3]));
</script></body><html>
我对正则表达式真的很陌生,所以这可能是一个非常简单的问题。
/(\w+)(\s*(\w+))?/
上面的正则表达式匹配“aaa”、“123”、“my_var”或“aaa bbb”等模式, “123 456”、“my_var my_value”。
对于像“aaa bbb”这样的表达式,matches = [“aaa bbb”,“aaa”,“bbb”,“bbb”]
,但是对于像“aaa”这样的表达式,匹配= ["aaa", "aaa", ???, ???]
首先让我感到惊讶的是 matches.length = 4。我原以为它是 2,但我没有看到任何文档解释它应该是什么。它是如何工作的?
让我感到惊讶的第二件事是,我得到的 2 个“额外”匹配项在我测试过的 2 个浏览器中的工作方式不同:
在 Firefox 3.6.3 中,matches[2] 和 matches[3] 未定义。
在 Internet Explorer 6 中,matches[2] 和 matches[3] 是一个空字符串。
基本上,我应该如何检查我的表达式是“短”(如“aaa”)还是“长”(如“aaa bbb”)?
最佳答案
标准 ( ECMAScript 5 ) 非常明确。长度应该是 4,而 IE 是错误的(令人震惊,我知道)。
从 §15.10.2.1 开始,“NcapturingParens 是左捕获括号的总数。”你有 3 个。
“状态是一个有序对(endIndex,捕获),其中endIndex是一个整数,< em>captures 是 NcapturingParens 值的内部数组。[...] captures 的第 n 个元素是表示由第 n 组捕获括号或 undefined 如果尚未达到第 n 组捕获括号。”
描述 exec 的 §15.10.6.2 说:
9 . d. i. Let r be the State result of the call to [[Match]]. [...]
12 . Let n be the length of r's captures array. (This is the same value as 15.10.2.1's NCapturingParens.)
13 . Let A be a new array created as if by the expression new Array() [...]
17 . Call the [[DefineOwnProperty]] internal method of A with arguments "length", Property Descriptor {[[Value]]: I + 1}, and true. [...]
20 . For each integer i such that I > 0 and I ≤ n
a. Let captureI be ith element of r's captures array.
b. Call the [[DefineOwnProperty]] internal method of A with arguments ToString(i), Property Descriptor {[[Value]]: captureI, [[Writable]: true, [[Enumerable]]: true, [[Configurable]]: true}, and true.
21 . Return A.
因此长度绝对应该是 4 (3 + 1),并且未达到的捕获(如模式中的 (\s*(\w+))
)保持未定义。幸运的是,undefined 和 ""(空字符串)都是假的。这意味着当它们被视为 bool 值时它们是假的。因此,您可以通过执行 if(matches[2])
关于javascript - Javascript 正则表达式中的问号(奇怪的行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098452/