Java .split(“|”) not working

Tags: , ,



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]

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 (&)


Source: stackoverflow