正则表达式分裂

时间:2015-11-01 17:57:29

标签: java regex

我试图将一个字符串分成"句子"但是我遇到了跟​​单词的问题。例如:

"This isn't cool. This doesn't work. This"

应分成

[This is cool., This doesn't work., This]

到目前为止,我一直在使用"[^\\.!?]*[\\.\\s!?]+",但无法弄清楚如何为尾随单词调整此值,因为没有终止字符,因此无需查找。有什么我可以添加或者我需要完全调整吗?

3 个答案:

答案 0 :(得分:2)

String s = "This isn't cool. This doesn't work. This";
System.out.println(Arrays.toString(s.split("\\. ")));

产地:

[This isn't cool, This doesn't work, This]

答案 1 :(得分:1)

除了分割字符串,您可以找到所有句子并匹配尾随句子,您可以使用锚点$,它将匹配字符串的结尾:

List<String> sentences = new ArrayList<String>();
 Matcher m = Pattern.compile("[^?!.]+(?:[.?!]|$)")
     .matcher("This isn't cool. This doesn't work. This");
 while (m.find()) {
   sentences.add(m.group());
 }

答案 2 :(得分:0)

您也可以安全地将最后+更改为*

默认情况下,正则表达式是 greedy ,每个单独的部分都会尽可能多地获取数据。这意味着第一个子表达式将匹配

This isn't cool

下一部分是时间和空间 - 仅此而已。将加号更改为星号不会更改此行为。在字符串中,所有句子结尾字符都会匹配,最后没有任何内容可供匹配 - 这对*有效。