Ese*_*far 2 java regex android replaceall
我有一个很长的文本,我试着在每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然后迭代以添加换行符:
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();
Run Code Online (Sandbox Code Playgroud)
但是我想自动使用:
src.replaceAll(regex2, "\n");
知道如何实现这一目标吗?
您可以使用以下正则表达式替换:
s = s.replaceAll("(?s)(.*?[.?!](?:\\s.*?[.?!]){0,2})\\s*", "$1\n");
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示
细节
(?s)- DOTALL修饰符(.现在匹配换行符)(.*?[.?!](?:\s.*?[.?!]){0,2}) - 第1组:
.*?[.?!]- 任何0+字符,尽可能少,直到最左边.,?或者!跟着(?:\s.*?[.?!]){0,2} - 0到2个序列
\s - 一个空白.*?[.?!]- 任何0+字符,尽可能少,直到最左边.,?或!\s+ - 一个或多个空格在$1\n更换发生除了最后一个空格整场比赛,并在最后追加换行符.