java split regex - 任何字符组合

时间:2013-06-28 08:03:04

标签: java regex

我使用3个字符拆分字符串:space,dash和逗号

我想要的是能够使用这3个字符的任意组合进行拆分,例如:

-,(短划线后跟逗号)或,--(逗号后跟2短划线)或- , -(短划线空格逗号空格短划线)等

    String address = "Sector -18B, Dwarka";
    String[] addressParts = address.split("[\\s+,-]");
    for (String part : addressParts) 
       System.out.println(part + " - " + part.isEmpty());

这给了我一个5长度数组:[“Sector”,“”,“18B”,“”,“Dwarka”]

我想要一个3长度数组:[“Sector”,“18B”,“Dwarka”]

我应该如何编写正则表达式?

2 个答案:

答案 0 :(得分:5)

您可以使用"(\\s|,|-)+"作为正则表达式

String address = "Sector -18B, Dwarka";
String[] addressParts = address.split("(\\s|,|-)+");
for (String part : addressParts) 
    System.out.println(part + " - " + part.isEmpty());

输出:

Sector - false
18B - false
Dwarka - false

答案 1 :(得分:2)

String address = "Sector -18B, Dwarka";
String[] addressParts = address.split("[\\s,-]+");
for (String part : addressParts){ 
System.out.println(part + " - " + part.isEmpty());
}