I have a string that's like this: 1|"value"|;
I want to split that string and have chosen | as the separator.
My code looks like this:
String[] separated = line.split("|"); What I get is an array that contains all characters as one entry:
separated[0] = "" separated[1] = "1" separated[2] = "|" separated[3] = """ separated[4] = "v" separated[5] = "a" ... Does anyone know why?
Can't I split an string with |?
You can use the split() method of java. lang. String class to split a string based on the dot. Unlike comma, colon, or whitespace, a dot is not a common delimiter to join String, and that's why beginner often struggles to split a String by dot.
You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.
The split() method divides the string at the specified regex and returns an array of substrings.
| is treated as an OR in RegEx. So you need to escape it:
String[] separated = line.split("\\|");
You have to escape the | because it has a special meaning in a regex. Have a look at the split(..) method.
String[] sep = line.split("\\|"); The second \ is used to escape the | and the first \ is used to escape the second \ :).
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