Regex: Get anything between any curly braces

Viewed 517

Regex noob here

I have the following string:

This is a message {key1} {{key2}} {{{key3}}}, and includes {key4}.

I'm trying to extract anything between the outer curly braces. Expected matches:

key1
{key2}
{{key3}}
key4

Most SO examples cover matches on a single curly brace or a double curly brace, but not both or any variation of. Expressions like [^{\}]+(?=}) will get me the content between the inner braces, and (?<=\{).*?(?=\}) will get the leading braces except the first, but not the trailing ones.

1 Answers

You may get the results you need using

var results = Regex.Matches(text, @"{({*[^{}]*}*)}")
        .Cast<Match>()
        .Select(x => x.Groups[1].Value);

See the regex demo.

Regex details

  • { - an open curly brace
  • ({*[^{}]*}*) - Group 1:
    • {* - 0 or more open curly braces
    • [^{}]* - 0 or more chars other than curly braces
    • }* - 0 or more close curly braces
  • } - a close curly brace
Related