2017-04-07 165 views

回答

2

您可以使用此正则表达式分裂。

RegEx Demo

输出:

hello 
- 
world 
how 
are 
you 
? 
+2

不是所有的空格,如'\ p {Z}'与选项卡不匹配。 –

+0

你说得对。 '\ p {javaWhitespace}'比'\ p {Z}'要好' – anubhava

-1

使用split的代码,这打破了在分离器中。对任何Unicode空格或向前看符号的帮助,如果一个或下一个字符是一个标点符号它断言

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})分裂:

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

    } 
+0

'hello-world' is connected – user3833308

+0

see StringTokenizer https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html – Pr3ds

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

要消除'if',你可以简单地使用'filter'。这将允许你写你的解决方案为'Arrays.stream(str.split(“\\ b +”))。filter(w - >!w.equals(“”))。forEach(System.out :: println) ;'。 – Pshemo

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, ?] 

见T他Java demo

详细

  • (?U) - 一个Pattern.UNICODE_CHARACTER_CLASS改性剂(使\w可以匹配Unicode字母)
  • \\w+ - 1+字字符(字母,数字,或_ - 可以用[\\w&&[^_]][^\\W_]
  • | - 或
  • \\p{Punct} - 标点符号(可能会替换为[\\p{P}\\p{S}])。
相关问题