javascript - Javascript 正则表达式中的问号(奇怪的行为)

标签 javascript regex

<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])

来解决 IE 的错误

关于javascript - Javascript 正则表达式中的问号(奇怪的行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098452/

相关文章:

javascript - react JS |当元素到达顶部

javascript - 结合用户滚动+动画css3/Javascript

java - java中用正则表达式表示回车和引号

c# - 从字符串中获取特定部分

javascript - 设置 cookie 为两个不同的值

javascript - 我确实有一个表单,其中如果用户输入内容,它应该检查负数或空输入框并抛出警报消息

javascript - 单击按钮时如何在div中显示值?

javascript - 正则表达式删除除数字之外的所有特殊字符?

URL 的 PHP 验证/正则表达式

.htaccess 中的正则表达式 - 如果在 HTTP_HOST 中找到一个 uri,我该如何 301?