2015-11-13 95 views
3

我有以下的样本数据:的Java通过拆分字符串 “^ | ^”

***^|^100^|^101^|^102^|^103^|^104^|^ 

我希望通过拆分 “^ | ^” 这样的结果将是:

*** 
100 
101 
102 
103 
104 

以下是我的示例代码,但未能获得预期的结果,我误解了分割模式?

String a = "***^|^100^|^101^|^102^|^103^|^104^|^105^|^106^|^107^|^108^|^"; 
String [] split ; 

split = a.split("^|^"); 
for(int i=0; i<split.length; i++) 
{ 
     System.out.println(split[i]); 
} 
+2

'分= a.split(“\\ \\^| \ \ ^“);'使用此 –

+0

http://stackoverflow.com/questions/21524642/splitting-string-with-pipe-character –

回答

12

两个^|是你需要转义特殊chatacters。

split = a.split("\\^\\|\\^"); 
12

使用Pattern.quote()把所有的元字符的字符串文字/文字图案。 ^,|在正则表达式中有特殊的含义。

这应该工作:

public static void main(String[] args) throws Exception { 
    String s = "***^|^100^|^101^|^102^|^103^|^104^|^"; 
    String pattern = Pattern.quote("^|^"); 
    System.out.println(Arrays.toString(s.split(pattern))); 

} 

O/P:

[***, 100, 101, 102, 103, 104] 
+1

我不知道模式。谢谢你看起来很棒。 –

+2

这看起来比通常的反斜线狂热更好。不过,我希望有一个拆分方法需要分隔符字符串,而不是正则表达式。 – Thilo

+0

@Thilo - Ya。这会让事情变得更简单:) – TheLostMind

-2

请检查该

String str = "***^|^100^|^101^|^102^|^103^|^104^|^"; 
String arr[] = str.split("\\^\\|\\^"); 
System.out.println(arr.length); 
+7

这个答案与Uma有什么不同? –