I have a split on a newline which works fine, but it seems to create a blank value for every time it does a split, so 'MyText' contains the following values, separated by a newline:


And my split is as below

List<string> options = myText.split('[\r\n]');

I instead of ending up with 3 'options' I end up with 5 like this - a blank for each newline:


Other than ignoring the blank values in a loop, how can I avoid the split creating the blanks in the first place?

2 Answers 2


If you split the string without the brackets, it works properly:

String myText = 'Blue\r\n'
              + 'Green\r\n'
              + 'Yellow';

List<string> options = myText.split('\r\n');

You're passing a regex to .split() for it to determine what to split on.

[] indicates a class of characters to match on.

so [\r\n] is telling you to split on a single character, either \r or \n.
It does not say "find an \r followed by \n". If your string happens to have both, then


will turn into



"Blue", "", Green

and so on

Keeping in mind that not every OS uses \r\n for line ends (it's pretty much just Windows that does that, I believe), the regex you want to use in .split() is \r?\n.

That's a carriage return (\r), which may or may not exist (?), followed immediately by a newline (\n)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .