繁体   English   中英

接受第一个非空regex.exec()捕获组

[英]Take first non-empty regex.exec() capturing group

假设我运行了这个

var text = "abc def ghi";
var regex = /a(bc)|d(e)f|(gh)i/g
while (match = regex.exec(text)) {
  console.log(match);
}
// 0=abc, 1=bc, 2=undefined, 3=undefined
// 0=def, 1=undefined, 2=e, 3=undefined
// 0=ghi, 1=undefined, 2=undefined, 3=gh

在循环的每次迭代中,我都想检索匹配的捕获组,因此只检索bc,e,gh。 是否可以不手动检查未定义?

我认为您不能避免进行检查(除非您可以使用Wiktor指出的环顾四周 ),但不必费劲:

 var text = "abc def ghi"; var regex = /a(bc)|d(e)f|(gh)i/g while (match = regex.exec(text)) { var first = match.reduce((p, entry, i) => p && i != 1 ? p : entry); console.log(first); } 

请注意,这将忽略所有虚假值,因为捕获组将根本不匹配(给您undefined )或匹配非空字符串,因此我们不必担心""

或者,代替

var first = match.reduce((p, entry, i) => p && i != 1 ? p : entry);

你可以用

var first = match.slice(1).reduce((p, entry) => p ? p : entry);

...但是它涉及一个临时数组。

您将获得match数组,因此您还可以添加逻辑,从末尾遍历数组并获得第一个undefined值。 如下所示:

 var text = "abc def ghi"; var regex = /a(bc)|d(e)f|(gh)i/g; var finalMatch = []; var match; while (match = regex.exec(text)) { for(var i=match.length; i>0; i--){ if(match[i]){ finalMatch.push(match[i]); break; } } } console.log(finalMatch); 

暂无
暂无

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

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