Regex smoothing around braces

I have a line like:

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

And I want it to be broken down into:

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

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

How do I save '{'and '}'? And how to remove the empty ""between '}'and '{'?

+4
source share
5 answers

Use Match All instead of Split

Remember that Match All and Split are two sides of the same coin .

Use this regex:

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

See matches in DEMO .

To see 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 rotation |, {[^}]*}corresponds{content in braces}
  • [^{}]+ , curlies
+5

:

String s = @"abc{d}efg{hi}{jk}lm{n}";
String[] parts = Regex.Split(s, @"(?<=^|})|(?={)");
foreach (string value in parts)
         Console.WriteLine(value);

abc
{d}
efg
{hi}
{jk}
lm
{n}
+1

, , , :

(?={)|(?<=})
+1

Try the following:

Parse the string until you go to the opening bracket. Bring a substring to this position. Parse the substrings after opening the parenthesis until a closing bracket is found. Print substrings between curly braces with curly braces. Continue this algorithm to the end of the line.

0
source

here is an easy way to do it

string to_split = "abc{d}efg{hi}{jk}lm{n}";
            var splited = Regex.Matches(to_split, @"\{[\w]*\}|[\w]*");
            foreach (Match match in splited)
            {
                Console.WriteLine(match.ToString());
            }
0
source

All Articles