首页 > 解决方案 > Javascript 匹配正则表达式行为

问题描述

我正在学习 Javascript 中的匹配运算符、捕获组等。但我很难理解以下内容是如何工作的。

var string = 'string of random words';
var match = string.match(/((random)|(words))/);
// returns array of 4 elements
0: "random"
1: "random"
2: "random"
3: undefined

我正在努力解决这个问题。我可以看到有一个管道字符,这意味着匹配字符串“随机”或“单词”。我可以看到 random 和单词在括号中,所以这是一个捕获组,整个表达式周围都有括号。

有人可以帮忙吗?

var string = 'string of random words';
var match = string.match(/((random)|(words))/);
console.log(match)

标签: javascriptregexmatch

解决方案


RegExp 匹配数组的第一个 ( [0]th) 元素是整个匹配。

不以括号(开头的括号(?:表示捕获组。((?:表示非捕获组)

第二个 ( [1]) 元素是第一个捕获组。如果组根本不匹配(例如,'foo'.match('(z)|(f)')),它将包含undefined.

match 数组的其他索引的行为方式相同 -[2]元素对应于第二个捕获组,[3]rd 元素对应于第三个捕获组,依此类推。

匹配数组将包含等于表达式中捕获组数加一的元素(对于位置 0 处的完全匹配)。

在这里,正在发生的事情是:

  • 完全匹配是random
  • 第一个捕获组包含整个匹配 - 与完整匹配相同,random
  • 第二个捕获组,在第一个捕获组内,但也恰好消耗了所有字符:random
  • 第三个捕获组,在第一个捕获组内:不匹配(因为|当正则表达式仅匹配左侧时,它位于 a 的右侧):包含undefined
/((random)|(words))/
  ^^^^^^^^^^^^^^^^^ First capture group (matched, contains "random")
/((random)|(words))/
   ^^^^^^           Second capture group (matched, contains "random")
/((random)|(words))/
            ^^^^^ Third capture group (not matched this time, so undefined)

如果您不熟悉正则表达式匹配数组,那么通过查看当组不都包含相同文本时会发生什么情况会更容易理解:

var string = 'abcdef';
var match = string.match(/ab(c(de)|(zzz))/);
console.log(match)

ab(c(de)|(zzz))
^^^^^^^^^^^^^^^ Full match (abcde)
ab(c(de)|(zzz))
   ^^^^^^^^^^^ First capture group (cde)
ab(c(de)|(zzz))
     ^^        Second capture group (de)
ab(c(de)|(zzz))
          ^^^  Third capture group (not matched, so undefined)

推荐阅读