将字符串数组中的一个句子拆分为特殊字符或空格

时间:2016-09-05 18:04:09

标签: java regex string split

我想将一个包含空格或任何特殊字符的句子分成带有空格或特殊字符的单词数组,也是数组的元素。

句子如:

aman,amit and sumit went to top-up 

应该拆分为String数组:

{"aman",",","amit"," ","and"," ","sumit"," ","went"," ","to"," ","top","-","up")

请使用java建议使用任何正则表达式或逻辑分割相同的内容。

我在问题中遗漏了一件事。我还需要拆分数字字符..但是使用split(“\ b”)不会拆分类似

的字符串
  

abc12def

进入

{ "abc", "12","def") or {"abc","1","2","def")

2 个答案:

答案 0 :(得分:0)

您似乎只需要匹配单词字符(\w+)或非单词字符(\W+)。将这些与交替运算符结合起来 - 或许 - 添加Pattern.UNICODE_CHARACTER_CLASS(或其内联/嵌入版本(?U))以使模式识别Unicode:

String value = "aman,amit and sumit went to top-up";
String pattern = "(?U)\\w+|\\W+";
List<String> lst = new ArrayList<>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(value);
while (m.find())
    lst.add(m.group(0));
System.out.println(lst);

请参阅Java demo

答案 1 :(得分:0)

我希望下面的代码段可以帮助您解决此问题。

public static void main(final String[] args) {
        String message = "aman,amit and sumit went to top-up";
        String[] messages = message.split("\\b");
        for(String string : messages) {
            System.out.println(string);
        }
    }