简体   繁体   中英

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.

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("\\|")

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

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

oracle docs on the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM