12

C#正規表現を使用して、文字列からすべてのインスタンスのペアの括弧を削除する方法を理解しようとしています。括弧とその間のすべてのテキストを削除する必要があります。括弧は常に同じ行にあるとは限りません。また、それらはネストされた括弧である可能性があります。文字列の例は次のようになります

This is a (string). I would like all of the (parentheses
to be removed). This (is) a string. Nested ((parentheses) should) also
be removed. (Thanks) for your help.

必要な出力は次のようになります。

This is a . I would like all of the . This  a string. Nested  also
be removed.  for your help.
4

4 に答える 4

22

幸いなことに、.NET では正規表現での再帰が許可されています (グループ定義のバランスを参照してください)。

Regex regexObj = new Regex(
    @"\(              # Match an opening parenthesis.
      (?>             # Then either match (possessively):
       [^()]+         #  any characters except parentheses
      |               # or
       \( (?<Depth>)  #  an opening paren (and increase the parens counter)
      |               # or
       \) (?<-Depth>) #  a closing paren (and decrease the parens counter).
      )*              # Repeat as needed.
     (?(Depth)(?!))   # Assert that the parens counter is at zero.
     \)               # Then match a closing parenthesis.",
    RegexOptions.IgnorePatternWhitespace);

誰かが疑問に思っている場合のために: 「括弧カウンター」は決してゼロを下回ることはありません (<?-Depth>そうでなければ失敗します) ()))((()

詳細については、Jeffrey Friedl の優れた本「Mastering Regular Expressions」 (p. 436) を参照してください。

于 2013-01-18T21:26:31.923 に答える
2

/\([^\)\(]*\)/gただし、一致するものが見つからなくなるまで、繰り返し空の文字列に置き換えることができます。

于 2013-01-18T21:26:38.963 に答える
1

通常、これはオプションではありません。ただし、Microsoft には、標準の正規表現に対する拡張機能がいくつかあります。Microsoft の拡張に関する説明を読んで理解するよりも、アルゴリズムとしてコーディングする方が速い場合でも、 Grouping Constructsを使用してこれを達成できる場合があります。

于 2013-01-18T21:30:38.410 に答える
0

これはどうですか:Regex Replaceがうまくいくようです。

string Remove(string s, char begin, char end)
{
    Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", begin, end));
    return regex.Replace(s, string.Empty);
}


string s = "Hello (my name) is (brian)"
s = Remove(s, '(', ')');

出力は次のようになります。

"Hello is"
于 2013-01-18T21:28:29.643 に答える