I’m looking for the simplest way to parse a string into groups – including the delimiters. What’s inside and outside the { } could be anything – except for { and }.
Using this
var s = "test {#}, {1} more text {a|b|c}";
var regEx = new Regex(@"{(.*?)}");
var mat = regEx.Matches(s);
I get groups that are ["{#}", "{1}", "{a|b|c}"].
My desired result is ["test ", "{#}", ", ", "{1}", " more text ", "{a|b|c}"].
>Solution :
If inside and outside can be anything except for { and }:
\{[^{}]*}|[^{}]+
Explanation
{Match the opening{[^{}]*Optionally match any char except{and}}Match the closing}|Or[^{}]+match 1+ chars other than{and}
Example
string pattern = @"{[^{}]*}|[^{}]+";
string input = @"test {#}, {1} more text {a|b|c}";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine("'{0}'", m.Value);
}
Output
'test '
'{#}'
', '
'{1}'
' more text '
'{a|b|c}'