Extract values within single curly braces

柔情痞子 提交于 2021-02-16 15:14:08

问题


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?


回答1:


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 }.


来源:https://stackoverflow.com/questions/38738558/extract-values-within-single-curly-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!