这个问题在这里已经有了答案:
How do you access the matched groups in a JavaScript regular expression?
(23 个回答)
3年前关闭。
我收到 Property 'groups' does not exist on type 'RegExpExecArray'
尝试时
const r = /\w+, (?<foo>\w+)/
const m = r.exec('hello, world')
if (m) {
const groups = m.groups
}
Javascript 可以选择调用
.groups
在正则表达式执行结果上。而且我知道输出实际上是一个数组……但是获取特定索引来获取组似乎有点麻烦。从列表中提取是 Typescript 中的唯一选项吗?
最佳答案
m[1] 将带来“世界”。
您可以作为 m['groups'] 访问组。
if (m) {
const groups = m['groups'];
}
因为如果你在 m 的 console.log/debug 你可以看到,groups 是一个来自结果的对象。如果您知道属性名称,则上面提到的是一种更具体的访问对象的方法。
关于regex - 如何从 Typescript 中的正则表达式 exec 匹配访问组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954432/