Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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
Regex 输出js正则表达式组匹配项_Regex - Fatal编程技术网

Regex 输出js正则表达式组匹配项

Regex 输出js正则表达式组匹配项,regex,Regex,我有这样一个字符串: hello [world (this is a string) with parenthesis](i'm in brackets too) 使用regex,我试图获得方括号[…]中包含的任何匹配项,以及圆括号(…)中包含的任何匹配项。我的一些字符串仅包含(…)和一些仅包含[…],其他字符串同时包含嵌套和分离,如上例所示 所以,我想要达到的结果是: 1. [world (this is a string) with parenthesis] 2. (this is a

我有这样一个字符串:

hello [world (this is a string) with parenthesis](i'm in brackets too) 
使用regex,我试图获得方括号[…]中包含的任何匹配项,以及圆括号(…)中包含的任何匹配项。我的一些字符串仅包含(…)和一些仅包含[…],其他字符串同时包含嵌套和分离,如上例所示

所以,我想要达到的结果是:

1. [world (this is a string) with parenthesis]
2. (this is a string)
3. (i'm in brackets too)
我认为1。第一组是比赛组,第二和第三组是第二组

我目前使用的代码和正则表达式是:

var str = "hello[world(this is a string) with parenthesis](i'm in brackets too)";
var re = /\[(.*?)\]|\((.*?)\)/g; // try and get all [] and ()

var match = re.exec(str.toString());

if (match) {
  // how do I output what are in square brackets
  // and what are in round brackets?
  // is it console.log(match[1]) for example ?? 
}
我在正则表达式中使用了|运算符,我认为这可能会影响我的结果。它是否在匹配时立即停止,而不捕获任何类型括号中的其他字符串

我遇到的主要问题是试图访问匹配的组-我原以为它们会在匹配[0]和匹配[1]中,因为我预期会有2个组,但当我console.log它们时,我得到了相同的结果


您的问题似乎是由您期望的匹配重叠(一个可能是另一个的一部分)这一事实引起的。因此,您只需将表达式包装成一个未经处理的正向前瞻:

(?=\[([^\]]*)\]|\(([^)]*)\))
下面是一个例子(我用更高效的求反字符类替换了惰性点匹配)

JS演示:

var re=/(?=\[([^\]]*)\]\\]\(([^]*)\)/g;
var str='hello[world(这是一个字符串)加括号](我也在括号中);
var-res=[];
while((m=re.exec(str))!==null){
如果(m.index==re.lastIndex){//这些行是必需的
re.lastIndex++;//正则表达式匹配一个空字符串
}
if(m[1]){//捕获组
res.push(m[1]);//保存我们需要的文本
}否则{
res.push(m[2]);
}
}

document.body.innerHTML=“+JSON.stringify(res,0,4)+”您的问题似乎是由您期望的匹配重叠(一个可能是另一个的一部分)这一事实引起的。因此,您只需将表达式包装成一个未经处理的正向前瞻:

(?=\[([^\]]*)\]|\(([^)]*)\))
下面是一个例子(我用更高效的求反字符类替换了惰性点匹配)

JS演示:

var re=/(?=\[([^\]]*)\]\\]\(([^]*)\)/g;
var str='hello[world(这是一个字符串)加括号](我也在括号中);
var-res=[];
while((m=re.exec(str))!==null){
如果(m.index==re.lastIndex){//这些行是必需的
re.lastIndex++;//正则表达式匹配一个空字符串
}
if(m[1]){//捕获组
res.push(m[1]);//保存我们需要的文本
}否则{
res.push(m[2]);
}
}
document.body.innerHTML=“+JSON.stringify(res,0,4)+”