Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split() string except for certain character combination

Tags:

c#

I want something like:

"aaaXaaaXaaaXaaaYXaaa".Split('X');

but want it to ignore 'YX'.

Of course I can simply loop and correct for it. But is there a built-in method for that?

like image 679
ispiro Avatar asked Jan 10 '13 14:01

ispiro


People also ask

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

Does string split remove delimiter?

. split() is a powerful string manipulation tool that we have at our disposal, but it can also be destructive. Splitting will remove delimiters from the returned array, which may give us output that differs greatly from what the original string was.

Can we use Regex in Split?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.


1 Answers

You can use a regular expression with a negative lookbehind:

string[] result = Regex.Split(s, "(?<!Y)X");

See it working online: ideone

More information about lookarounds: Lookahead and Lookbehind Zero-Width Assertions

like image 139
Mark Byers Avatar answered Oct 05 '22 19:10

Mark Byers