简体   繁体   English

Java奇怪的拆分行为 字符

[英]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) addere>要添加>(1)

Split ">" outcome 分割“>”结果
[addere, to add, (1)] [加法,加法(1)]

Split "|" 分割“ |” outcome 结果
[, a, d, d, e, r, e, |, t, o, , a, d, d, |, (, 1, )] [,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. 然后,您必须对Java本身使用反斜杠。 Try: 尝试:

text.split("\\|")

Since | 由于| is a meta character,It works when you escape that. 是一个元字符,当您转义该字符时,它就起作用。

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

oracle docs on the same 甲骨文文档在同一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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