When doing a .split() on a String in Java delimited with the "|" pipe character, remember to perform double escape (see explanation below). Example:
String string = "boo|and|foo";
Because of how the pipe is used in a regular expression, what one would expect to do as in splitting a typical comma-separated value list,
string.split("|");
However it does not work the same way, and the result would be a messed up array
[, b, o, o, |, a, n, d, |, f, o, o]
Instead, this should be done:
string.split("\\|");
in order to get the desired result of
[boo, and, foo]
Explanation:
The pipe needs to be escaped from the string, but in order for the backslash to be included to let Java know that the pipe is to be escaped, the backslash itself has to be escaped first! Regex has other plans for the pipe character thus inadvertently causing this situation.
No comments:
Post a Comment