2011-06-20 48 views
2

我在的形式得到的字符串:拆分對轉義空間

/path/ /path\ with\ space/ /another/ 

我需要拆分這使我結束了包含數組:

[ /path/, /path with space/, /another/ ] 

有一個簡單的正則表達式那會照顧到這個?以前我使用\ s +,但顯然這不起作用。

回答

6

使用negative lookbehind

String s = "/path/ /path\\ with\\ space/ /another/"; 
String[] parts = s.split("(?<!\\\\)\\s+"); 

System.out.println(Arrays.toString(parts)); 
// prints [/path/, /path\ with\ space/, /another/] 

注意,第二個元素仍含有\ s,這則需要去掉自己。

for (int i=0; i<parts.length; i++) 
{ 
    parts[i] = parts[i].replaceAll("\\\\ ", " "); 
} 

System.out.println(Arrays.toString(parts)); 
// prints [/path/, /path with space/, /another/] 

是的,這是 \就是爲了要匹配字符串在一個單一的一個。

+0

啊,這很有趣,不知道分裂是否與這樣的逆序工作。涼! – alexcoco

+0

很好,謝謝! –

1

如果在每個比賽結束後將其分割在「/」(注意空格)並追加正斜槓怎麼辦?我不確定分割是否會影響後面。