4

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

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

当然,这真的读

ABCD

有没有一种算法可以消除这样的字符串中不必要的括号?

4

2 回答 2

2

此函数将删除所有没有后跟量词且不是环视的组。它假定 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)?)。这将需要更长的标记模式。

于 2010-06-08T18:17:16.257 回答
0

1)使用理解括号的解析器

2)使用可以匹配括号的Perl递归正则表达式(在这种情况下不鼓励恕我直言)我认为Boost regex不支持所需的递归类型。

3)也许他们是需要的?别管他们。

于 2010-06-07T20:34:00.353 回答