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

前端 未结 4 1980
梦如初夏
梦如初夏 2020-12-09 19:17

I am trying to figure out how to use C# regular expressions to remove all instances paired parentheses from a string. The parentheses and all text between them should be rem

相关标签:
4条回答
  • 2020-12-09 19:48

    How about this: Regex Replace seems to do the trick.

    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, '(', ')');
    

    Output would be:

    "Hello is"
    
    0 讨论(0)
  • Normally, it is not an option. However, Microsoft does have some extensions to standard regular expressions. You may be able to achieve this with Grouping Constructs even if it is faster to code as an algorithm than to read and understand Microsoft's explanation of their extension.

    0 讨论(0)
  • 2020-12-09 19:56

    Fortunately, .NET allows recursion in regexes (see Balancing Group Definitions):

    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);
    

    In case anyone is wondering: The "parens counter" may never go below zero (<?-Depth> will fail otherwise), so even if the parentheses are "balanced" but aren't correctly matched (like ()))((()), this regex will not be fooled.

    For more information, read Jeffrey Friedl's excellent book "Mastering Regular Expressions" (p. 436)

    0 讨论(0)
  • 2020-12-09 20:04

    You can repetitively replace /\([^\)\(]*\)/g with the empty string till no more matches are found, though.

    0 讨论(0)
提交回复
热议问题