CodeGuy
CodeGuy

Reputation: 28907

Splitting a String in Java

I have a string as follows

String s = "3|4||5 9|4 0|0 4 8|..."

and I want to split it based on the "|" appearances. As such, the split should return

["3","4","5 9","4 0,"0 4 8",...]

But, in Java,

s.split("|") = [, 3, |, 4, ...]

In other words, it is splitting by the "" character, it seems. What is wrong?

Upvotes: 1

Views: 152

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

Note that public String[] split(String regex) takes a regex.

Since | is a meta character,It works when you escape the special character.

String[] results = result.split("\\|");

or(personally recommending this)

String[] result = result.split(Pattern.quote("|"));

If you use Pattern

Now, | will be treated as normal character | and not as the regex meta char |.

Oracle explained here why \\

Upvotes: 2

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You can try like below

 s.split("[|]")

Upvotes: 1

rgettman
rgettman

Reputation: 178243

The | character has special meaning in regular expressions, so you must escape it with a backslash. Then you must escape the backslash itself for Java. Try:

s.split("\\|")

The Javadocs for the Pattern class has lots of details about special characters in regular expressions. See the "Logical operators" section in that page for what | does.

Upvotes: 5

Related Questions