簡體   English   中英

C#Regex - 如何從字符串中刪除多個配對的括號

[英]C# Regex - How to remove multiple paired parentheses from string

我試圖弄清楚如何使用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.

幸運的是,.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);

如果有人想知道:“parens計數器”可能永遠不會低於零( <?-Depth>否則會失敗),所以即使括號是“平衡的”但沒有正確匹配(如()))((() ),這個正則表達式不會被愚弄。

欲了解更多信息,請閱讀Jeffrey Friedl的優秀着作“掌握正則表達式” (第436頁)

您可以重復地用空字符串替換/\\([^\\)\\(]*\\)/g ,直到找不到更多匹配項。

通常,它不是一種選擇。 但是,Microsoft確實對標准正則表達式進行了一些擴展。 您可以通過Grouping Constructs實現這一點,即使編寫算法編碼速度快於閱讀和理解Microsoft對其擴展的解釋。

怎么樣: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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM