Dil Dil - 1 month ago 17
C# Question

Split constantly on the last delimiter in C#

I have the following string:

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


The result I want is a list of length four with the following substrings:

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


In other words, how do I split on the last occurrence when the delimiter is repeating multiple times? Thanks.

Answer

You need to use a regex based split:

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

See the C# demo

The ;(?!;) regex matches any ; that is not followed with ;.

To also avoid matching a ; at the end of the string (and thus keep it attached to the last item in the resulting list) use ;(?!;|$) where $ matches the end of string (can be replaced with \z if the very end of the string should be checked for).