我正在尝试执行以下操作:
String[] Res = Text.split("[\\p{Punct}\\s]+");
但是,我总是收到一些前面有空格的单词。 如何解析句子而不将空格和其他标点符号作为单词本身的一部分?
最佳答案
由于您没有提供可以重现问题的示例输入,我只能猜测。我不明白为什么你提供的正则表达式应该在结果中留下空格,除非你使用非 ASCII 空格或标点符号。 \\p{Punct}
和 \\s
的原因都是 POSIX 字符类仅限于 ASCII,例如\\s
不会匹配 \u00a0
。如果您遇到非 ASCII 标点符号和空白字符的问题,请使用 [\\p{IsPunctuation}\\p{IsWhite_Space}]+
。
示例
String text="Some\u00a0words stick together⁈";
String[] res1 = text.split("[\\p{Punct}\\s]+");
System.out.println(Arrays.toString(res1));
String[] res2 = text.split("[\\p{IsPunctuation}\\p{IsWhite_Space}]+");
System.out.println(Arrays.toString(res2));
将产生:
[Some words, stick, together⁈]
[Some, words, stick, together]
关于java - Java中按标点符号分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811111/