Search code examples
c#regexregexp-replace

Regex to replace all curly braces except for the case '{0}'


I want to validate a string:

  • it may contain zero to many occurrences of {0}
  • all other occurrences of { or } must be removed.

So: 'AbC{de{0} x{1}}' must become 'AbCde{0} x1'

I tried this:

value = Regex.Replace(value, @"({|})+(?!{0})", string.Empty);

But that gives me the error:

Regex issue: Quantifier(x,y) following nothing.

What is wrong?


Solution

  • You may use

    Regex.Replace(text, @"(\{0})|[{}]", "$1")
    

    Or, to support any ASCII digits inside {...},

    Regex.Replace(text, @"(\{[0-9]+})|[{}]", "$1")
    

    See the regex demo

    Details

    • (\{0}) - Capturing group 1 ($1 refers to this value from the replacement string): a {0} substring
    • | - or
    • [{}] - a { or }.

    Another approach with lookarounds is possible:

    Regex.Replace(text, @"{(?!0})|(?<!{0)}", string.Empty)
    

    See another regex demo. Here, {(?!0}) matches a { not followed with 0} and (?<!{0)} matches a } not preceded with {0.