Java按空格和标点符号拆分字符串,但结果中只包含标点符号

时间:2017-04-07 20:17:17

标签: java regex

hello-world how are you?

应该导致

hello
-
world
how
are 
you
?

这是我试过的代码

String str = "Hello-world how are you?";
Arrays.stream(str.split("\\b+")).forEach(System.out::println);

4 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式进行拆分:

String str = "hello-world how are you?";
Arrays.stream(str.split("\\p{javaWhitespace}+|(?=\\p{P})|(?<=\\p{P})")).forEach(System.err::println);

这里\\p{Z}+|(?=\\p{P})|(?<=\\p{P})在任何unicode空格上分割,或者在前导或下一个字符是标点字符的情况下,在它前面断言的情况下断言。

RegEx Demo

<强>输出:

hello
-
world
how
are
you
?

答案 1 :(得分:1)

String str = "Hello-world how are you?";
Arrays.stream(str.split("\\b+")).forEach(w -> {
    if (!w.equals(" "))
        System.out.println(w);
});

答案 2 :(得分:1)

使用匹配方法可以实现更简单的正则表达式解决方案:

String str = "Hello-world how are yóu?";
List<String> res = new ArrayList<>();
Matcher m = Pattern.compile("(?U)\\w+|\\p{Punct}").matcher(str);
while (m.find()) {
    res.add(m.group());
}
System.out.println(res);
// => [Hello, -, world, how, are, yóu, ?]

请参阅Java demo

<强>详情:

  • (?U) - Pattern.UNICODE_CHARACTER_CLASS修饰符(以便\w可以匹配Unicode字母)
  • \\w+ - 1个单词字符(字母,数字或_ - 可以使用[\\w&&[^_]][^\\W_]减去
  • | - 或
  • \\p{Punct} - 标点符号(可以替换为[\\p{P}\\p{S}])。

答案 3 :(得分:-1)

使用split,这打破了分隔符。

public static void main(String[] args) {
        String test = "hello - word bla bla bla";
        String[] values = test.split(" ");

        for (String element : values) {
            System.out.println(element);
        }

    }