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

[英]Searching for a unique value across multiple parenthesis with RegEx on JavaScript?


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.

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

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/12/05/1497d9b200c8a3eadebd8cf2a32ff022.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告