Missing parentheses with Regex

后端 未结 4 938
轮回少年
轮回少年 2020-12-29 14:21

Am I correct in thinking that Regex can\'t be used to detect missing parentheses (because there is no way of counting pairs)? Using JavaScript I\'ve about a thousand strings

4条回答
  •  -上瘾入骨i
    2020-12-29 15:17

    You can't do the recursion in the regex itself, but you can always do it in JavaScript.

    Here is an example:

    // First remove non-brackets:
    string=string.replace(/[^{}[\]()]/g,"");
    // Then remove bracket pairs recursively
    while (string!==oldstring) {
      oldstring=string;
      string=string.replace(/({}|\[\]|\(\))/g,"");
    }
    

    The remainder are the non-matching brackets.

    Live demo: http://jsfiddle.net/3Njzv/

    If you need to count the pairs, you can do the replacements one at a time and add a counter:

    // First remove non-brackets:
    string=string.replace(/[^{}[\]()]/g,"");
    
    // Then remove bracket pairs recursively
    var counter=-1;
    while (string!==oldstring) {
      counter ++;
      oldstring=string;
      string=string.replace(/({}|\[\]|\(\))/,"");
    }
    

提交回复
热议问题