Escaping the "|" sign in java

I need to split a spring delimited by "|". When I use String.split("|") it doesn't give me the correct result.

String[] arr = "1234|5678".split("|"); System.out.println(arr[1]); \\ This prints "1"

I've tried using the escape character "\" but I get an Invalid escape sequence error from Eclipse.

What am I missing ?

Jon Skeet
people
quotationmark

You need to understand that there are two levels of escaping here:

  • String literal escaping
  • Regular expression escaping

You want a regular expression with the pattern \| - but in order to write that as a string literal, you need to escape the \, so you end up with:

split("\\|")

Another alternative is to use something like Guava's Splitter which is simpler to use because it doesn't treat strings as regular expressions - although it does allow you to specify a Pattern when you want a regular expression:

Splitter splitter = Splitter.on('|');
...
List<String> list = splitter.splitToList("1234|5678");

people

See more on this question at Stackoverflow