C# Regex.Match curly brackets- contents only? (exclude braces)
I always liked it explicit. So you can use "positive lookbehind" (?<=...) and "positive lookahead" (?=...) groups:
(?<=\{)
[^}]*
(?=\})
which means:
- require opening curly bracket before match
- collect text (of, course) - as commented before I may be [^{}]* as well
- require closing curly bracket after match
In C#, as in many other programming language, the regex engine supports capturing groups, that are submatches, parts of substrings that match a whole regex pattern, defined in a regex pattern with the help of parentheses (e.g. 1([0-9])3
will match 123
and save the value of 2
into a capture group 1 buffer). Captured texts are accessed via Match.Groups[n].Value
where n is the index of the capture group inside the pattern.
Capturing is much more effecient that lookarounds. Whenever there is no need for complex conditions, capturing groups are much better alternatives.
See my regex speed test performed at regexhero.net:
Now, how can we get the substring inside curly braces?
- if there is no other curly braces inside, with a negated character class:
{([^{}]*)
- if there can be nested curly brackets:
{((?>[^{}]+|{(?<c>)|}(?<-c>))*(?(c)(?!)))
In both cases, we match an opening {
, and then match (1) any character other than {
or }
, or (2) any characters up to the first paired }
.
Here is sample code:
var matches = Regex.Matches("Test {Token1} {Token 2}", @"{([^{}]*)");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();
Console.WriteLine(String.Join(", ", results));
matches = Regex.Matches("Test {Token1} {Token {2}}", @"{((?>[^{}]+|{(?<c>)|}(?<-c>))*(?(c)(?!)))");
results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();
Console.WriteLine(String.Join(", ", results));
Result: Token1, Token 2
, Token1, Token {2}
.
Note that RegexOptions.IgnoreCase
is redundant when you have no literal letters that can have different case in the pattern.
Thanks Milosz Krajewski, Nothing to add but here is the function
private List<String> GetTokens(String str)
{
Regex regex = new Regex(@"(?<=\{)[^}]*(?=\})", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(str);
// Results include braces (undesirable)
return matches.Cast<Match>().Select(m => m.Value).Distinct().ToList();
}
Just move the braces outside the parentheses:
{([^}]*)}
It is regex for C# .net.
@"{(.*?)}"
it display a
token1 token2