在每 x 个句子后打破一个字符串

Break a String after every x sentences

我的文章很长,我试着每 3 句话就把它打断。

例子

来源:

"Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5. Sentence 6. Sentence 7. Sentence 8. Sentence 9. Sentence 10."

应该return:

"Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5. Sentence 6. Sentence 7. Sentence 8. Sentence 9. Sentence 10."

目前我的正则表达式 (?<=[\.?!])\s 匹配句子之间的所有空格。所以我可以用它来拆分字符串,然后像这样迭代添加换行符:

String[] splits = src.split(regex);
StringBuilder b = new StringBuilder();
int index = 0;
for (String s : splits) {
    if (index == 3) {
        b.append("\n");
        index = 0;
    } else if (index > 0) {
        b.append(" ");
    }

    b.append(s);
    index++;
}
String res = b.toString();

但我想自动使用:

src.replaceAll(regex2, "\n");

知道如何实现吗?

您可以使用以下正则表达式替换:

s = s.replaceAll("(?s)(.*?[.?!](?:\s.*?[.?!]){0,2})\s*", "\n");

regex demo

详情

  • (?s) - DOTALL 修饰符(. 现在匹配换行字符)
  • (.*?[.?!](?:\s.*?[.?!]){0,2}) - 第 1 组:
    • .*?[.?!] - 任何 0+ 个字符,尽可能少,直到最左边的 .?!,然后是
    • (?:\s.*?[.?!]){0,2} - 0 到 2 个序列
      • \s - 一个空格
      • .*?[.?!] - 任何 0+ 个字符,尽可能少,直到最左边的 .?!
  • \s+ - 1 个或多个空格

\n 替换采用除最后一个空格外的整个匹配项,并在末尾附加换行符。