0

I am trying to split a string as follows

String string = "mike|ricki"

If I do the following string.split("|") I would expect an array of 2 elements, "mike" and "ricki". Instead I am getting the following

[, m, i, k, e, |, r, i, c, k, i]

Am i doing something fundamentally wrong here?

Biscuit128
  • 5,218
  • 22
  • 89
  • 149
  • Related [Using split() with “|” character](http://stackoverflow.com/questions/20409916/using-split-with-character) – Pshemo Aug 01 '14 at 20:21

3 Answers3

3

Yes. Pipe character | is a special character in regular expressions. You must escape it by using \. The escape string would be \|, but in Java the backslash \ is a special character for escape in literal Strings, so you have to double escape it and use \\|:

String[] names = string.split("\\|");
System.out.println(Arrays.toString(names));
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

If you read the String.split() Java Documentation, it says that it can receive a Regular Expression as an input.

The Pipe character | is a special character in regular expressions so if you want to use it as a literal you have to escape it like \\|

So your code have to be:

String[] splitted = string.split("\\|");

EDIT : Corrected sample code.

Roberto Linares
  • 2,215
  • 3
  • 23
  • 35
0

String.split takes a regular expression. The pipe character has a special meaning in regex so it's not matching as you were expecting.

Try String.split("\\|") instead.

The backslash tells regex to treat the pipe as a literal character.

Paolo
  • 22,188
  • 6
  • 42
  • 49