我有一篇很长的课文,我试着每三句话就把它打断。
例子
来源:"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."
目前我有一个regex(?<=[\.?!])\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*", "$1\n");
参见regex demo
细节
(?s)
-dotall修饰符(.
现在匹配换行符)(.*?[.?!](?:\s.*?[.?!]){0,2})
-第1组:.*?[.?!]
-任何0+字符,尽可能少,最左边的.
,?
或!
紧跟其后(?:\s.*?[.?!]){0,2}
-0到2个序列\s
-空格.*?[.?!]
-任何0+字符,尽可能少,最左边.
,?
或!
\s+
-1个或多个空白$1\n
替换将获取除最后一个空格之外的所有匹配项,并在末尾追加换行符。