PreguntonCojoneroCabrón PreguntonCojoneroCabrón - 4 months ago 11
C# Question

Extract values within single curly braces

I want to get a collection {value} of a string using Regular Expression.

For example:


lorem ipsum {field1} lorem ipsum {field2} lorem ipsum field1 lorem ipsum field2 {{field3}}


I would get:
{field1} and {field2}


I try this:

string pattern =@"\[(?>[^\{\}]+)*\]";

MatchCollection matches = Regex.Matches(text, pattern);
for (int ctr = 0; ctr < matches.Count; ctr++)
{
string field = matches[ctr].Value;
// ... ommitted...
}


Any suggestions?

Answer

You can use negative lookarounds to only get the {...} substrings not having { in front or } right after them:

(?<!{){[^{}]+}(?!})

See the regex demo

enter image description here

  • (?<!{) - a negative lookbehind failing the match if there is a { before the current position
  • { - a literal {
  • [^{}]+ - 1 or more symbols other than { and }
  • } - a literal }
  • (?!}) - a negative lookahead failing the match if there is } right after the previous }.
Comments