正则表达式匹配字符串与包含闭括号

时间:2017-02-22 16:39:41

标签: javascript regex pattern-matching match

我需要创建正则表达式规则以匹配字符串与不是'包含( )字符以及包含它们但始终关闭(但不是嵌套)的字符串。另一个空()的内容也是错误的

好的字符串(应该匹配):

aaaaaa
(asdasd)
aaaa(bbb)a
(aaa)aaaa
aaaaaa(aaaa)
aaaa(bbb)(ccc)ddd
aaaa(bbbb)cccc(dddd)eeee

坏字符串(不应该匹配):

)aaaa
)aaaa(asd)
aaaaaa(
aaaa(bbb))
aaa(bbb
aaaaa((bbbb)cccc
aaaa(bbbb))ccc
aaaa(aasd(adssad))ad
adassd(aas(add)adsa(asda)ad)
()

尝试并创建了类似(?!.*[(]{2,})(?!.*[)]{2,})(?![)])(?!.*[(]$).*$之类的东西,但它仍然不是很好。对此有何帮助?

2 个答案:

答案 0 :(得分:2)

如果要检查平衡的parens,可以使用如下函数:

function balanced(str) {
  var a = 0;
  for(var i = 0; i < str.length; i++) {  // for each character in str
    if(str.charAt(i) == '(') a++;        // if it's an open paren, increment a
    else if(str.charAt(i) == ')') a--;   // if it's a close one, decrement a
  }
  return a == 0;                         // if a == 0 then it's balanced (true), if not then it's not balanced (false)
}

var s1 = "aaaa(bbbb)cccc(dddd)eeee";
var s2 = "aaaa(bbbb(cccc(dddd)eeee";
var s3 = "aaaa";

console.log(s1 + " => " + balanced(s1));
console.log(s2 + " => " + balanced(s2));
console.log(s3 + " => " + balanced(s3));

或者如果你坚持使用正则表达式,那么使用两个正则表达式来检查这样的平衡parens:

function balanced(str) {
  var opened = str.match(/\(/g);      // match open parens
  var closed = str.match(/\)/g);      // match close parens
  opened = opened? opened.length: 0;  // get the count of opened parens, if nothing is matched then 0
  closed = closed? closed.length: 0;  // get the count of closed parens, if nothing is matched then 0
  return opened == closed;            // balanced means the count of both is equal
}

var s1 = "aaaa(bbbb)cccc(dddd)eeee";
var s2 = "aaaa(bbbb(cccc(dddd)eeee";
var s3 = "aaaa";

console.log(s1 + " => " + balanced(s1));
console.log(s2 + " => " + balanced(s2));
console.log(s3 + " => " + balanced(s3));

答案 1 :(得分:0)

这应该可以解决问题:

^([^()]|\([^()]+\))+$

读取&#34;匹配不是paren或(这里没有parens),一次或多次,整个字符串&#34;

如果你想在任何级别匹配平衡的parens,由于缺乏递归支持,js中不可能有单个表达式,但函数将相当简单。

&#13;
&#13;
let balanced = function(s) {
  var re = /\([^()]*\)/g
  while (s.match(re)) s = s.replace(re, '')
  return !s.match(/[()]/)
}

console.log(balanced('a(b((d))e) (f) g'))
console.log(balanced('a(b((d))e? (f) g'))
&#13;
&#13;
&#13;

或没有正则表达式:

&#13;
&#13;
let balanced = s => {

    let c = 0;

    for (let x of s) {
        if (x == '(') c++;
        if (x == ')' && !c--) return false;
    }

    return !c;
};
&#13;
&#13;
&#13;