我有一根绳子像:

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

我想把它分成:
"abc","{d}","efg","{hi}","{jk}","lm","{n}"

我使用了这个模式,结果是[{}]
我该如何保持"abc","d","efg","hi","","jk","lm","n"'{'在那里?如何移除'}'""之间的空'}'

最佳答案

使用“全部匹配”而不是“拆分”
记住Match All and Split are Two Sides of the Same Coin
使用此正则表达式:

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

查看DEMO中的匹配项。
要查看匹配项:
var myRegex = new Regex("{[^}]*}|[^{}]+");
Match matchResult = myRegex.Match(yourString);
while (matchResult.Success) {
    Console.WriteLine(matchResult.Value);
    matchResult = matchResult.NextMatch();
}

解释
在交替|的左侧,{[^}]*}匹配{content in braces}
在右侧,[^{}]+匹配任何不是卷曲的字符

07-24 09:51