Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with a delimiter that can be repeated adjacent without getting empty parts?

How to split a string using a delimiter when the delimiter can be next to each other and the first delimiter should be part of the string?

Eg:

ABC::XYZ:QUI

The split should be:

1) ABC:
2) XYZ
3) QUI

Split(':') does not works.

like image 464
NoobProg Avatar asked Dec 19 '25 10:12

NoobProg


1 Answers

You may split on the regex pattern :(?!:):

string input = "ABC::XYZ:QUI";
string[] parts = Regex.Split(input, @":(?!:)");
foreach (string part in parts)
{
    Console.WriteLine(part);
}

This prints:

ABC:
XYZ
QUI

The regex here uses a negative lookahead to ensure that we only split/consume on : which is not followed by another :.

like image 192
Tim Biegeleisen Avatar answered Dec 20 '25 23:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!