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
System.out.print(strbuf[i]+" ");
The output i get is :
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("|"));