【问题标题】:Break a String after every x sentences每 x 个句子后断开一个字符串
【发布时间】:2017-10-25 12:26:05
【问题描述】:

我有一个很长的文本,我尝试在每 3 句话后将其中断。

示例

来源:

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

应该返回:

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

知道如何实现这一目标吗?

【问题讨论】:

标签: java android regex replaceall


【解决方案1】:

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

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

regex demo

详情

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

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

【讨论】:

  • 完美答案。
  • 非常感谢。完美运行。但我不确定是否正确理解(?s) 的作用?
  • @Eselfar (?s) - 一个 DOTALL 修饰符(. 现在匹配换行符)。默认情况下,点不跨行匹配。
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2022-10-26
  • 2019-07-01
  • 2021-07-05
  • 1970-01-01
  • 2018-08-22
  • 2018-10-01
相关资源
最近更新 更多