私が(JavaScriptの正規表現で)持っているとします
((((A)B)C)D)
もちろん、それは本当に読みます
ABCD
そのような文字列で不要な括弧を削除するアルゴリズムはありますか?
私が(JavaScriptの正規表現で)持っているとします
((((A)B)C)D)
もちろん、それは本当に読みます
ABCD
そのような文字列で不要な括弧を削除するアルゴリズムはありますか?
この関数は、数量詞が続かないすべてのグループを削除し、ルックアラウンドではありません。ECMAScriptフレーバー正規表現を想定しており、capture-groups((
... )
)は重要ではありません。
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"
括弧にトークン()が1つだけ含まれているかどうかを判別しようとはしません(A)?
。それには、より長いトークン化パターンが必要になります。
1) 括弧を理解するパーサーを使用する
2)括弧に一致するPerlの再帰的正規表現を使用します(この場合はお勧めしません)Boost正規表現が必要なタイプの再帰をサポートしているとは思いません。
3) おそらく必要ですか?放っておけ。