有没有一种特定的方法可以在JavaScript RegEx匹配中检索组

Is there a specific method for retrieving groups in JavaScript RegEx matches?

本文关键字:RegEx JavaScript 检索 方法 一种 有没有      更新时间:2023-09-26

假设我在JavaScript:中有这个字符串

var candidates = "hillary clinton sanders clinton bush"

然后我使用这个RegEx匹配,并在这个数组中获得匹配组:

candidates.match(/clinton ([a-z]+) ([a-z]+)/)
=> [
    'clinton sanders clinton',
    'sanders',
    'clinton',
    index: 8,
    input: 'hillary clinton sanders clinton bush'
]

是否有任何方法或方法只检索匹配的组?而不必确切知道有多少?在python中,我通过执行以下操作来实现这一点:

import re
test = "rowing"
temp = re.compile(r"([a-z]+)ing")
temp.match(test).groups()
---> "row"

当regex中有组时,匹配在js中的工作方式是,它总是在索引0处具有完全匹配,而数组的其余部分将包含组。所以你可以做一些类似 var match = candidates.match(/clinton ([a-z]+) ([a-z]+)/); if (match) match = match.slice(1, match.length); 的事情

匹配将只包含组。你可以把这个逻辑放在一个函数中。