Java:带管道特殊字符的split()方法 [英] Java: split() method with pipe special character

查看:237
本文介绍了Java:带管道特殊字符的split()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String =Hello-new-World。当我使用具有不同正则表达式值的split()方法时,它的行为不同。

I have a String = "Hello-new-World". And when i use the split() method with different regex values, it acts differently.

String str = "Hello-new-world"
String[] strbuf=str.split("-");
for(int i=0;i<strbuf.length;i++)
 System.out.print(strbuf[i]+" ");

我得到的输出是:

hello
new
world

如果我将我的字符串更改为Hello | new | world,我会得到一个完全不同的答案。新输出变为:

whereas if i change my string to "Hello|new|world", i get an altogether different answer. The new output becomes:

h
e
l
l
o
|
n
e
w
|
w
o
r
l
d

可以有人请解释可能的原因。

Can someone please explain what could be the possible reason for this.

推荐答案

据推测,你正在拆分 |在第二种情况下 - 而 | 在正则表达式中具有特殊含义。如果你想拆分实际的管道字符,你应该将其转义:

Presumably you're splitting on "|" in the second case - and | has a special meaning within regular expressions. If you want to split on the actual pipe character, you should escape it:

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

这篇关于Java:带管道特殊字符的split()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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