Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split string into groups by inside and outside of brackets – including the brackets

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}"].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }

Regex demo

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}'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading