You should probably use using
statements instead of writing out the namespace in full every time. At first glance your code looks quite complex but when you remove all the namespaces it turns out to be very simple. Also the OfType
is not needed.
The regular expression should match as much as possible which isn't an open brace [^{]*
or else an open brace, some text and then a closing brace {[^}]*}
. The regular expression for this is:
{[^}]*}|[^{]*
Try this code:
string text = "abcdef{123}ghi{456}kl";
Regex regex = new Regex("{[^}]*}|[^{]*");
foreach (Match match in regex.Matches(text))
{
Console.WriteLine(match.Value);
}
Output:
abcdef
{123}
ghi
{456}
kl
Note: this regular expression does not validate that the string is in the correct format, it assumes that it is well-formed.
A slightly simpler method is to use Split instead of Matches and include a capturing group in the regular expression so that the separator is also included in the output:
string text = "abcdef{123}ghi{456}kl";
Regex regex = new Regex("({[^}]*})");
foreach (string part in regex.Split(text))
{
Console.WriteLine(part);
}
The output for this is the same as above.