[英]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.