Java奇怪分裂行为与|字符 [英] Java Strange split behavior with | character

查看:129
本文介绍了Java奇怪分裂行为与|字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小文件,其中包含一些内容,我想用|字符。



当我尝试使用任何其他字符(例如>)时,它工作正常,但是|






行本身(这里用>字符)

addere>添加>(1)



拆分>结果

[addere,to add,(1)]



拆分|结果

[,a,d,d,e,r,e,|,t,o,a,d,d,|,(,1, >




为什么要拆分所有内容,甚至忽略|字符本身中的字符?

提前感谢。

解决方案

反斜杠,因为它的含义在正则表达式中是特殊的。然后你必须为Java本身转义反斜杠。尝试:

  text.split(\\ |)


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

这篇关于Java奇怪分裂行为与|字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆