felix fritz
felix fritz

Reputation: 462

Java Strange split behavior with | character

I have a little file that contains some content that I want to split with the "|" character.

When I tried it with any other character (eg. ">"), it worked perfectally fine, but with the "|" character, there were some unexpected outcomes.


The line itself (here with the > character)
addere>to add>(1)

Split ">" outcome
[addere, to add, (1)]

Split "|" outcome
[, a, d, d, e, r, e, |, t, o, , a, d, d, |, (, 1, )]


Why is it splitting everything and even ignoring the "|" character in the string itself?
Thanks in advance.

Upvotes: 0

Views: 90

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

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

String[]  array =youString.split("\\|");

oracle docs on the same

Upvotes: 1

rgettman
rgettman

Reputation: 178263

You must escape the pipe character with a backslash, because its meaning is special in a regex. Then you must escape the backslash for Java itself. Try:

text.split("\\|")

Upvotes: 4

Related Questions