简体   繁体   中英

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 '{' ?

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

Use a combination of lookaround assertions:

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

Output

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

未经测试但希望这将适用于您的分裂:

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

Try the following:

Parse the string until you get to an opening brace. Output the substring until that position. Parse the substrings after the opening brace until a closing brace is found. Output the substrings between the braces with the braces. Continue this algorithm until end of string.

here is a simple 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());
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM