javascript - 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)
解决方案
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)
推荐阅读
- python - 打印字符串与添加到列表不同,为什么?
- python - 做什么
在函数名中是什么意思? - java - 密钥库操作失败:填充模式不兼容
- javascript - 共享后端和前端输入验证或模块
- c - C中的免费未初始化指针
- c# - Json 反序列化 - 如何将剩余项目添加到字典中?
- python - Keras Lambda 层给出 ValueError: Input 0 is incompatible with layer xxx: expected min_ndim=3, found ndim=2
- python - 使用 python 请求库时出现“socket.timeout:超时”错误
- node.js - 在 MEAN 堆栈应用程序中无法获取/错误
- sql-server - 不同列的不同过滤器