JavaScript 中全局正则表达式匹配的清理数组解构
Clean array destructuring of global regex matches in JavaScript
这更多是出于好奇,但是否有一种干净的方法可以循环遍历全局正则表达式的匹配项并在一行中解构每个匹配项?我能想到的最干净的方法是:
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()
成员(这可能无论如何都是理想的解决方案)。
为什么不稍后解构一行:
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;
//...
}
这更多是出于好奇,但是否有一种干净的方法可以循环遍历全局正则表达式的匹配项并在一行中解构每个匹配项?我能想到的最干净的方法是:
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()
成员(这可能无论如何都是理想的解决方案)。
为什么不稍后解构一行:
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;
//...
}