简体   繁体   中英

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?

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

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

See the regex demo

在此输入图像描述

  • (?<!{) - 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 } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM