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 '{'
?
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
|
, the {[^}]*}
matches {content in braces}
[^{}]+
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.