2

我正在使用 3 个字符拆分字符串:空格、破折号和逗号

我想要的是能够使用这 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"]

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

4

2 回答 2

5

You can use "(\\s|,|-)+" as the regex pattern

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

Output:

Sector - false
18B - false
Dwarka - false
于 2013-06-28T08:19:19.627 回答
2
String address = "Sector -18B, Dwarka";
String[] addressParts = address.split("[\\s,-]+");
for (String part : addressParts){ 
System.out.println(part + " - " + part.isEmpty());
}
于 2013-06-28T08:30:28.060 回答