Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.split need pipe delimiter to be escaped?

Tags:

java

string

regex

People also ask

How do you split a string without delimiter?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split a string with escape characters?

split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression. The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !

When splitting a string using a given separator it returns?

The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

How do you escape a pipe character in Java?

use \\| instead of | to escape it.


String.split expects a regular expression argument. An unescaped | is parsed as a regex meaning "empty string or empty string," which isn't what you mean.


Because the syntax for that parameter to split is a regular expression, where in the '|' has a special meaning of OR, and a '\|' means a literal '|' so the string "\\|" means the regular expression '\|' which means match exactly the character '|'.


You can simply do this:

String[] arrayString = yourString.split("\\|");