You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SpringBoot中使用PDFBox为PDF各段落添加分隔符

解决PDFBox提取文本时添加段落分隔符的问题

你当前的代码仅判断文本末尾是否存在\n\n并追加分隔符,只能处理最后一处段落间隔,无法覆盖所有段落间的分隔。要实现每个段落间插入分隔符的需求,需要全局替换所有连续的段落换行,而非仅处理文本末尾。

解决方案

使用正则表达式匹配所有连续2个及以上的换行(兼容Windows的\r\n和Unix的\n),将其替换为「换行+分隔符+换行」的格式,既能在每段之间插入分隔符,又能保留原有的段落换行结构。

代码示例

String DELIMITER = "-";
// 匹配所有连续2个及以上的换行,替换为带分隔符的段落间隔
text = text.replaceAll("(\r?\n){2,}", "\n\n" + DELIMITER + "\n\n");

效果验证

针对你提供的PDF文本,替换后会生成如下结果:

This is a small demonstration .pdf file -

-

just for use in the Question. More text. And more
text. And more text. And more text. And more text.

-

And more text. And more text. And more text. And more text. And more
text. And more text. Boring, zzzzz. And more text. And more text. And
more text. And more text. And more text. And more text. And more text.
And more text. And more text.

-

完全符合你需要的输出格式。

内容的提问来源于stack exchange,提问作者S Sidharth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:30:51