Java .split("|") not working

You can try to escape it like this:

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

Pipe has special meaning in regular expression and it allows regular expression components to be logically ORed. So all you need to escape it using the \\


| is a regular expression key character and split() works with regualar expressions. Escape it like this: \\|


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

Tags:

Java

String

Split