javascript – 删除正则表达式中不必要的括号

假设我有(在
javascript正则表达式中)

((((A)B)C)D)

当然,这真的是读

ABCD

是否有算法消除字符串中不必要的括号?

最佳答案 此函数将删除未跟随量词的所有组,并且不是环顾四周.它假设ECMAScript风格正则表达式,捕获组((…))是不重要的.

function removeUnnecessaryParenthesis(s) {
   // Tokenize the pattern
   var pieces = s.split(/(\\.|\[(?:\\.|[^\]\\])+]|\((?:\?[:!=])?|\)(?:[*?+]\??|\{\d+,?\d*}\??)?)/g);
   var stack = [];
   for (var i = 0; i < pieces.length; i++) {
      if (pieces[i].substr(0,1) == "(") {
         // Opening parenthesis
         stack.push(i);
      } else if (pieces[i].substr(0,1) == ")") {
         // Closing parenthesis
         if (stack.length == 0) {
            // Unbalanced; Just skip the next one.
            continue;
         }
         var j = stack.pop();
         if ((pieces[j] == "(" || pieces[j] == "(?:") && pieces[i] == ")") {
             // If it is a capturing group, or a non-capturing group, and is
             // not followed by a quantifier;
             // Clear both the opening and closing pieces.
             pieces[i] = "";
             pieces[j] = "";
         }
      }
   }
   return pieces.join("");
}

例子:

removeUnnecessaryParenthesis("((((A)B)C)D)")  --> "ABCD"
removeUnnecessaryParenthesis("((((A)?B)C)D)") --> "(A)?BCD"
removeUnnecessaryParenthesis("((((A)B)?C)D)") --> "(AB)?CD"

它不会尝试确定括号是否只包含一个标记((A)?).这将需要更长的标记化模式.

点赞