Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Split Around Curly Braces

I have a string like :

"abc{d}efg{hi}{jk}lm{n}"

And I want it to be split into:

"abc","{d}","efg","{hi}","{jk}","lm","{n}"

I used this pattern [{}] and the result is "abc","d","efg","hi","","jk","lm","n"

How do I keep the '{'and'}' there? And how do I remove the empty "" between '}'and'{'?

like image 775
Sean C. Avatar asked Jul 31 '14 04:07

Sean C.


1 Answers

Use Match All instead of Split

Remember that Match All and Split are Two Sides of the Same Coin.

Use this regex:

{[^}]*}|[^{}]+

See the matches in the DEMO.

To see the matches:

var myRegex = new Regex("{[^}]*}|[^{}]+");
Match matchResult = myRegex.Match(yourString);
while (matchResult.Success) {
    Console.WriteLine(matchResult.Value);
    matchResult = matchResult.NextMatch();
} 

Explanation

  • On the left side of the alternation |, the {[^}]*} matches {content in braces}
  • On the right side, [^{}]+ matches any chars that are not curlies
like image 110
zx81 Avatar answered Sep 21 '22 23:09

zx81