繁体   English   中英

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

[英]Java split string by whitespace and punctuation but include only punctuation in result

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);

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

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空格上分割或借助前向断言来断言上一个或下一个字符是否是标点符号。

正则演示

输出:

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

匹配的方法可以使正则表达式更简单:

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演示

详细资料

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

使用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);
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM