Last Updated: February 25, 2016
·
20.39K
· segunfamisa

Escape the pipe!

Hi guys,
For some reason, this never occurred to me until today.

If you're going to use the split() method on a String object in Java using the pipe character ( "|" ) as the regex match, you'll need to escape the pipe.

String input = "234|Nigeria";

String code = input.split("|")[0];
String country = input.split("|")[1];

String escapedCode = input.split("\\|")[0];
String escapedCountry = input.split("\\|")[1];

System.out.println("Unescaped: " + code + "," + country);
System.out.println("Escaped: " + escapedCode + "," + escapedCountry);

The output is as shown below:

Unescaped: ,2
Escaped: 234,Nigeria