Home >Java >javaTutorial >Why Does Java's `split()` Method Fail When Splitting Strings by '|' and How Can I Fix It?
The Java split() method, when used to divide a string by the pipe symbol ("|"), can yield unexpected results, as seen in the following example:
public static void main(String[] args) { String test = "A|B|C||D"; String[] result = test.split("|"); for (String s : result) { System.out.println(">"+s+"<"); } }
Instead of the intended output:
>A< >B< >C< >< >D<
the code produces:
>< >A< >| >B< >| >C< >| >| >D<
Why does this occur?
The problem lies in the syntax of the split() method. The pipe symbol, "|", holds special significance in regular expressions, where it represents the "OR" operator. To use the pipe symbol literally as a delimiter, it must be escaped using a backslash ().
To amend the code, one can use the following approaches:
// Option 1: Escaping the pipe symbol String[] result = test.split("\|");
// Option 2: Utilizing Pattern.quote() import java.util.regex.Pattern; String[] result = test.split(Pattern.quote("|"));
By escaping the pipe symbol, you suppress its special status in regular expressions, allowing it to be interpreted as a literal delimiter.
The above is the detailed content of Why Does Java's `split()` Method Fail When Splitting Strings by '|' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!