Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取第一个非空的regex.exec()捕获组_Javascript_Regex - Fatal编程技术网

Javascript 获取第一个非空的regex.exec()捕获组

Javascript 获取第一个非空的regex.exec()捕获组,javascript,regex,Javascript,Regex,让我们假设我运行这个 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

让我们假设我运行这个

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。是否可以不手动检查未定义项?

我不认为您可以避免检查(除非您可以使用lookarounds作为),但它不需要长篇大论:

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

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

var text=“abc def ghi”;
var regex=/a(bc)| d(e)f |(gh)i/g;
var finalMatch=[];
var匹配;
while(match=regex.exec(text)){
对于(var i=match.length;i>0;i--){
if(匹配[i]){
最终匹配推送(匹配[i]);
打破
}
}
}

控制台日志(最终匹配)这在JS RegExp中是不可能的。您必须检查
未定义的
。或者依赖lookarounds(注意lookbehind是目前在Chrome中实现的ECMAScript 2018功能):
/(?问题的关键在于是否可以不进行手动检查