简体   繁体   English

JavaScript中全局正则表达式匹配的干净数组销毁

[英]Clean array destructuring of global regex matches in JavaScript

This is more out of curiosity than anything else, but is there a clean method of looping over the matches of a global regex and destructuring each match in one line? 出于好奇,这比什么都重要,但是是否存在一种干净的方法来遍历全局正则表达式的匹配项并在一行中破坏每个匹配项? The cleanest approach I can think of is: 我能想到的最干净的方法是:

 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); } 

If you don't include the || [] 如果不包括|| [] || [] , it tries to destructure null which throws an error. || [] ,它尝试解构null并引发错误。 The empty array is truthy, so the best method I can think of is to check its length. 空数组是真实的,因此我能想到的最好方法是检查其长度。 Since you can't wrap a let statement in parentheses and then call a member of it, the variable declaration needs to happen outside the scope of the while which is undesirable. 由于您不能将let语句包装在括号中,然后再调用它的成员,因此变量声明需要在while范围之外进行while这是不可取的。

Ideally there'd be a clever way to avoid the || [] 理想情况下,有一种避免|| []的聪明方法。 || [] , but I haven't thought of one, short of adding a matches() member to RegExp.prototype (which might just be the ideal solution anyway). || [] ,但我没有想到一个,只是向RegExp.prototype添加一个RegExp.prototypematches()成员(无论如何这可能是理想的解决方案)。

Why not just destructure one line later: 为什么不稍后再破坏一行:

 let part; 
 while(part = regex.exec(str)) {
   const [match, a, ...otherCaptures] = part;
   //...
 }

With a for loop the part can also be local scoped: 使用for循环,该part也可以在本地范围内:

 for(let part; part = regex.exec(str); ) {
   const [match, a, ...otherCaptures] = part;
   //...
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM