2013-03-23 107 views
0

我有一個像'[1] - [2] - [3],[4] - [5],[6,7,8],[9]'或'[Computers ] - [蘋果] - [筆記本電腦],[電纜] - [電纜,連接器],[適配器],我希望模式獲得列表結果,但不知道如何弄清楚模式。基本上逗號是分割,但[6,7,8]本身也包含逗號。使用正則表達式分割字符串

the string: [1]-[2]-[3],[4]-[5],[6,7,8],[9] 
the result: 
[1]-[2]-[3] 
[4]-[5] 
[6,7,8] 
[9] 

or 

the string: [Computers]-[Apple]-[Laptop],[Cables]-[Cables,Connectors],[Adapters] 
the result: 
[Computers]-[Apple]-[Laptop] 
[Cables]-[Cables,Connectors] 
[Adapters] 
+0

你可以給這個代碼樣本輸出? – 2013-03-23 04:43:29

+1

分割'',['。 – 2013-03-23 04:44:00

+1

哦,我明白了。這不是真正的正則表達式,你可以使用簡單的分割。 – 2013-03-23 04:44:33

回答

0

雖然我相信在這裏的最好方法是使用分裂(由@ j__m的答案呈現)這是一種使用匹配而不是分裂的方法。

正則表達式:

(\[.*?\](?!-)) 

用法示例:

String input = "[Computers]-[Apple]-[Laptop],[Cables]-[Cables,Connectors],[Adapters]"; 
Pattern p = Pattern.compile("(\\[.*?\\](?!-))"); 
Matcher m = p.matcher(input); 
while (m.find()) { 
    System.out.println(m.group(1)); 
} 

結果輸出:

[Computers]-[Apple]-[Laptop] 
[Cables]-[Cables,Connectors] 
[Adapters] 
+0

謝謝你。這正是我想要的。你是冠軍:) – user1629480 2013-03-23 06:00:49

3
,(?=\[) 

這種模式分割上後跟一個托架任何逗號,但保持結果文本內的支架。

(?=*stuff*)被稱爲「超前斷言」。它作爲比賽的條件,但不是比賽的一部分。

在C#代碼:

String inputstring = "[Computers]-[Apple]-[Laptop],[Cables]-[Cables,Connectors],[Adapters]"; 
foreach(String s in Regex.Split(inputstring, @",(?=\[)")) 
    System.Console.Out.WriteLine(s); 

在Java代碼:

String inputstring = "[Computers]-[Apple]-[Laptop],[Cables]-[Cables,Connectors],[Adapters]"; 
Pattern p = Pattern.compile(",(?=\\[)")); 
for(String s : p.split(inputstring)) 
    System.out.println(s); 

無論是生產:

[Computers]-[Apple]-[Laptop] 
[Cables]-[Cables,Connectors] 
[Adapters] 
+0

我有一個模式,但它會將[6,7,8]分成三部分,它是「」[^「」\ r \ n] *「」|'[^^'\ r \ n] *'| [^,\ r \ n] * – user1629480 2013-03-23 05:04:58

+0

我的模式特別保留[6,7,8] – 2013-03-23 05:06:17

+0

您能否詳細說明您的模式。我試過你的模式,但它不起作用 – user1629480 2013-03-23 05:12:20

0

不使用正則表達式(如果那是值得的東西的回答在易於理解的情況下)是:

  1. 替代 「] @ [」 爲 「],[」
  2. 分裂的 「@」
+1

如果字符串有任何'@'符號開頭,你運氣不好。另一個答案提供了一個更好的解決方案,不會遇到這個問題。 – Vulcan 2013-03-23 04:56:21