2013-03-23 15 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

相关问题