使用JavaScript上的RegEx在多个括号中搜索唯一值?

时间:2022-12-06 23:37:07

Example

var value = "foo bar (foo(bar)(foo(bar)))";

And the value you want is

而你想要的价值是

(foo(bar)(foo(bar)))

And not

(foo(bar)

2 个解决方案

#1


1  

As elclarns notes, JS doesn't have recursive regex, but regex is not the only tool, parenthesis counter should work, well

正如elclarns指出的那样,JS没有递归正则表达式,但正则表达式不是唯一的工具,括号计数器应该工作,以及

  var x = "foo bar (foo(bar)(foo(bar))) foo bar";
  var result = "";
  var cnt = 0;
  var record = false;
  for(var i=0; i<x.length; ++i) {
    var ch = x.charAt(i);
    if(ch=="(") { ++cnt; record = true; }
    if(ch==")") --cnt;
    if(record) result+= ch;
    if(record && !cnt) break;
  }
  if(cnt>0) record = ""; // parenthesis not enclosed

  console.log(result); // (foo(bar)(foo(bar)))

This of course captures only the first parenthesis, but you can record them all in array and choose the longest result. This should be easy.

这当然只捕获第一个括号,但您可以将它们全部记录在数组中并选择最长的结果。这应该很容易。

#2


0  

this should work.

这应该工作。

var re = /\(.*\)/
var result = re.exec(value) //["(foo(bar)"]

It then will catch the biggest string between parenthesis.

然后它将捕获括号之间的最大字符串。

#1


1  

As elclarns notes, JS doesn't have recursive regex, but regex is not the only tool, parenthesis counter should work, well

正如elclarns指出的那样,JS没有递归正则表达式,但正则表达式不是唯一的工具,括号计数器应该工作,以及

  var x = "foo bar (foo(bar)(foo(bar))) foo bar";
  var result = "";
  var cnt = 0;
  var record = false;
  for(var i=0; i<x.length; ++i) {
    var ch = x.charAt(i);
    if(ch=="(") { ++cnt; record = true; }
    if(ch==")") --cnt;
    if(record) result+= ch;
    if(record && !cnt) break;
  }
  if(cnt>0) record = ""; // parenthesis not enclosed

  console.log(result); // (foo(bar)(foo(bar)))

This of course captures only the first parenthesis, but you can record them all in array and choose the longest result. This should be easy.

这当然只捕获第一个括号,但您可以将它们全部记录在数组中并选择最长的结果。这应该很容易。

#2


0  

this should work.

这应该工作。

var re = /\(.*\)/
var result = re.exec(value) //["(foo(bar)"]

It then will catch the biggest string between parenthesis.

然后它将捕获括号之间的最大字符串。