【发布时间】: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");
知道如何实现这一目标吗?
【问题讨论】:
-
您可能希望使用
"(?s).*?[.?!](?:\\s.*?[.?!]){0,2}"模式匹配它们 -
@WiktorStribiżew 看起来很完美。
标签: java android regex replaceall