Why Does String.Split Need Pipe Delimiter to Be Escaped

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

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.

Splitting string with pipe character ( | )

| is a metacharacter in regex. You'd need to escape it:

String[] value_split = rat_values.split("\\|");

| not recognized in java string.split() method

You should escape it:

String words[] = word.split("\\|");

Check this explanation in similar question here: Why does String.split need pipe delimiter to be escaped?

String object's split() method has a regular expression as a parameter. That means an unescaped | is not interpreted as a character but as OR and means "empty string OR empty string".

How to split a string in java with a specified delimiter while ignoring /?

Just use

split("\\x7C")

or

split("\\|")

You need to escape or use corresponding unicode value when splitting against the pipeline char '|'.

String.Split - Unexpected behaviour

Yes. Pipe character | is a special character in regular expressions. You must escape it by using \. The escape string would be \|, but in Java the backslash \ is a special character for escape in literal Strings, so you have to double escape it and use \\|:

String[] names = string.split("\\|");
System.out.println(Arrays.toString(names));

Why I cannot split string with $ in Java

The method String.split(String regex) takes a regular expression as parameter so $ means EOL.

If you want to split by the character $ you can use

String arrStr[] = str.split(Pattern.quote("$"));

Java split String at |

Please, escape the character:

String[] parts = match.split("\\|");

Split a String on | (pipe) in Java

| is a special symbol in regular expression. Use \\| instead.

I'll explain why I appended 2 slashes. To escape the |, I need \|. However, to represent the string \|, "\\|" is required because \ itself needs to be escaped in a string lateral.

And, as xagyg has pointed out in the comment, split will treat the parameter as a regular expression. It will not be treated as a plain string.

In this use case, you may be interested to learn about Pattern.quote. You can do Pattern.quote("|"). This way, none of the characters will be treated as special ones.



Related Topics



Leave a reply



Submit