在 C# 中的最后一个定界符处不断拆分

Split constantly on the last delimiter in C#

我有以下字符串:

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

我想要的结果是一个长度为 4 的列表,包含以下子字符串:

"hello"
"there;"
"you;;"
"!"

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

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

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

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

您可以使用此代码:

string s = "hello;there;;you;;;!;";
MatchCollection matches = Regex.Matches(s, @"(.+?);(?!;)");

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

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

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

C# demo

;(?!;) 正则表达式匹配任何未跟随 ;;

为了避免匹配字符串末尾的 ;(从而使其附加到结果列表中的最后一项)使用 ;(?!;|$),其中 $ 匹配字符串结尾(如果应该检查字符串的结尾,可以用 \z 替换)。