Java官方文档指出:
"boo:and:foo"例如,字符串使用这些表达式生成以下结果Regex结果:
{ "boo", "and", "foo" }"
Run Code Online (Sandbox Code Playgroud)
这就是我需要它工作的方式.但是,如果我运行这个:
public static void main(String[] args){
String test = "A|B|C||D";
String[] result = test.split("|");
for(String s : result){
System.out.println(">"+s+"<");
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
><
>A<
>|<
>B<
>|<
>C<
>|<
>|<
>D<
Run Code Online (Sandbox Code Playgroud)
这远非我所期望的:
>A<
>B<
>C<
><
>D<
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
我想知道为什么我不能拆分包含|的文本 作为String中的分隔符.当我使用逗号等时,分裂工作正常.
这是一个SSCE
package tests;
public class Tests {
public static void main(String[] args) {
String text1="one|two|three|four|five";
String text2="one,two,three,four,five";
String [] splittedText1 = text1.split("|");
String [] splittedText2 = text2.split(",");
for(String elem : splittedText1) System.out.println("text1="+elem);
for(String elem : splittedText2) System.out.println("text2="+elem);
}
}
Run Code Online (Sandbox Code Playgroud)
任何想法为什么它不适用于"|" ??