You should probably use using statements instead of writing a namespace each time. At first glance, your code looks rather complicated, but when deleting all namespaces it turns out to be very simple. OfType also not required.
The regular expression must match the maximum possible, which is not an open bracket [^{]* , or an open bracket, some text, and then a closing bracket {[^}]*} . 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); }
Conclusion:
abcdef
{123}
ghi
{456}
kl
Note: this regular expression does not confirm that the string is in the correct format, it assumes that it is well formed.
A slightly simpler way is to use Split instead of Matches and include the capture group in the regular expression so that the delimiter 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.
source share