2017-02-22 100 views
1

我需要创建的正则表达式规则与犯规匹配字符串”包含有他们内部,而是一直处于关闭状态(但没有嵌套()字符,并且同样的字符串正则表达式匹配字符串。另一件事,空()也是错误的用含有封闭括号

良好的字符串(应选配):

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,})(?![)])(?!.*[(]$).*$,但它仍然不好。任何帮助?

+1

多少级可以有?这是一个好串还是坏串:'aaa(bb(cc)bb)'? –

+0

圆括号的一个级别是可以实现的。固定数量的水平是可以实现的,但不是实用的,只有几个水平。任意嵌套不再是一种常规语言。 – 9000

回答

3

您可以使用此正则表达式为你的工作:

/^(?!$)(?:[^)(]*\([^()]+\))*[^)(]*$/gm 

RegEx Demo

正则表达式破碎:

  • ^ - 行启动
  • (?!$) - 负前瞻,以确保我们不匹配emp TY串
  • (?: - 开始非捕获组
    • [^)(]*的 - 匹配0个或更多的什么,但()
    • \( - 匹配一个(
    • [^()]+ - 第1场或更多的东西但是()
    • \) - 匹配文字)
  • )* - 非捕获组的结束,*使得它匹配0或多次
  • [^)(]* - 匹配0个或更多的什么,但()
  • $ - 行结束
+0

不必要的复杂和冗长,不需要匹配'[^)(]'两次。 – georg

+0

@georg:它可能看起来比较长,但会比'^([^()] | \([^()]你可能想用'“))来检查你的函数)x)(((”'))+ $'(你可以检查在regex101上采取的步骤# – anubhava

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));

或者,如果你坚持使用正则表达式,然后使用两个正则表达式来检查平衡的括号是这样的:

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

) – georg

0

这应该做的伎俩:

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

阅读“ma tch不是paren或(这里没有parens),一次或多次,整个字符串“

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

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'))

或没有正则表达式:

let balanced = s => { 
 

 
    let c = 0; 
 

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

 
    return !c; 
 
};