问题
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