One way we can use this is to use a backslash \ . For example: string. split("\\|");
Java split() function is used to splitting the string into the string array based on the regular expression or the given delimiter. The resultant object is an array contains the split strings. In the resultant returned array, we can pass the limit to the number of elements.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
Use proper escaping: string.split("\\|")
Or, in Java 5+, use the helper Pattern.quote()
which has been created for exactly this purpose:
string.split(Pattern.quote("|"))
which works with arbitrary input strings. Very useful when you need to quote / escape user input.
Use this code:
public static void main(String[] args) {
String test = "A|B|C||D";
String[] result = test.split("\\|");
for (String s : result) {
System.out.println(">" + s + "<");
}
}
You could also use the apache library and do this:
StringUtils.split(test, "|");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With