假设我在 JavaScript 中有这个字符串:
var candidates = "hillary clinton sanders clinton bush"
然后我使用这个正则表达式匹配并在这个数组中获取我的匹配组:
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"
最佳答案
匹配在 js 中的工作方式,当你在正则表达式中有组时,它总是在索引 0 处具有完整匹配,并且数组的其余部分将包含组。所以你可以做类似 的事情
var match =候选人.match(/克林顿([a-z]+)([a-z]+)/);
if (match) match = match.slice(1, match.length);
匹配仅包含组。您可以将此逻辑放入函数中。
关于javascript - 是否有在 JavaScript RegEx 匹配中检索组的特定方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557849/