这更多的是出于好奇心,但是有没有一种干净的方法可以循环遍历全局正则表达式的匹配,并在一行中解析每个匹配?我能想到的最干净的方法是:
let regex = /(a)(b)?(c*)/g,
str = 'cabcccaccaaabbacb',
match, a, otherCaptures;
while (([match, a, ...otherCaptures] = regex.exec(str) || []).length) {
// do stuff
console.log(match, a, otherCaptures);
}
如果不包含|| []
,它会尝试解析null
,这会抛出一个错误。空数组是真实的,所以我能想到的最好的方法就是检查它的长度。由于您不能将let
语句包装在圆括号中,然后调用它的成员,因此变量声明需要发生在while
范围之外,这是不可取的。
理想情况下,会有一种聪明的方法来避免|| []
,但除了向RegExp.prototype
添加matches()
成员之外,我还没有想过这样的方法(这可能是最理想的解决方案)。
发布于 2018-10-16 04:36:48
为什么不在后面解构一行代码:
let part;
while(part = regex.exec(str)) {
const [match, a, ...otherCaptures] = part;
//...
}
使用for循环,part
也可以是局部作用域:
for(let part; part = regex.exec(str); ) {
const [match, a, ...otherCaptures] = part;
//...
}
https://stackoverflow.com/questions/52824346
复制相似问题