关于.net:在C#的最后一个定界符中不断分割

Split constantly on the last delimiter in C#

我有以下字符串:

1
string x ="hello;there;;you;;;!;"

我想要的结果是长度为4的列表,带有以下子字符串:

1
2
3
4
"hello"
"there;"
"you;;"
"!"

换句话说,当定界符重复多次时,如何在最后一次出现时拆分?谢谢。


您需要使用基于正则表达式的拆分:

1
2
3
4
var s ="hello;there;;you;;;!;";
var res = Regex.Split(s, @";(?!;)").Where(m => !string.IsNullOrEmpty(m));
Console.WriteLine(string.Join(",", res));
// => hello, there;, you;;, !

请参阅C#演示

;(?!;)正则表达式与后跟;的任何;匹配。

为避免在字符串末尾与;匹配(并使其与结果列表的最后一项保持联系),请使用;(?!;|$),其中$与字符串末尾匹配(可以替换为\\z(如果应检查字符串的最末端)。


您似乎不想删除空条目,但要保留分隔符。

您可以使用以下代码:

1
2
3
4
5
6
7
string s ="hello;there;;you;;;!;";
MatchCollection matches = Regex.Matches(s, @"(.+?);(?!;)");

foreach(Match match in matches)
{
    Console.WriteLine(match.Captures[0].Value);
}


1
2
3
4
5
string x ="hello;there;;you;;;!;"
var splitted = x.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptryEntries);

foreach (var s in splitted)
    Console.WriteLine("{0}", s);