C# Regular expression pattern what this matches for

c#, regex

Solution

It looks for a `{...}` with some (1 or more) `non-}` inside. If successful it puts the content of the `{...}` in capture group 1.

Regex x = new Regex("{([^}]+)}");
var m = x.Match("{Hello}");

string str0 = m.Groups[0].ToString(); // {Hello}
string str1 = m.Groups[1].ToString(); // Hello

Group 0 is always the whole match.

var m2 = x.Match("{}");
var success = m2.Success; // false

It isn't anchored, so it could have more than one match for each string...

var m2 = x.Matches("{Hello}{}{World}");
int c = m2.Count; // 2 matches. The {} wasn't a match, {Hello} and {World} were

As a sidenote, if you think this is the beginning for a good C# parser, you are on the wrong road :-) Expressions like `{ { string str = "Hello"; } str += "x"; }` will confuse this regex, so expressions like `{ string str = "}" }`. This is a stackless regex. No fancy tricks.

Problem

Can sombody explain what this regex will check for ``` Regex x = new Regex("{([^}]+)}"); ```

Original source