Skip to content
Advertisement

Java .split(“|”) not working

I just ran into the problem that the split method for strings wouldn’t work with character “|” as an argument. It somehow separates each character in the string.

Code:

String[] res = "12345|6".split("|");
Log.d("split", Arrays.toString(res));

Output:

splitīš• [, 1, 2, 3, 4, 5, |, 6]

Advertisement

Answer

Use escape character before | like below:

String[] res = "12345|6".split("\|");

Similar “escape character logic” is required, when you are dealing/splitting with any of the below special characters (used by Regular Expression):

  • OR sign (|)
  • question mark (?)
  • asterisk (*)
  • plus sign (+)
  • backslash ()
  • period (.)
  • caret (^)
  • square brackets ([ and ])
  • dollar sign ($)
  • ampersand (&)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement