使用RegEx拆分字符串

时间:2013-03-23 04:42:21

标签: regex

我有一个字符串,如'[1] - [2] - [3],[4] - [5],[6,7,8],[9]'或'[Computers] - [Apple] - [笔记本电脑],[电缆] - [电缆,连接器],[适配器]',我喜欢Pattern获取列表结果,但不知道如何弄清楚模式。基本上逗号是分割,但[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]

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

不使用正则表达式的答案(如果值得理解正在发生的事情)是:

  1. 替换“] @ [”for“],[”
  2. 拆分为“@”

答案 2 :(得分:0)

虽然我认为这里最好的方法是使用split(如@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]
相关问题