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

如何使正则表达式匹配至句子结尾停止,同时按指定长度拆分文本

解决方案

需求回顾

  • 文本拆分规则1:按指定字符长度(最多14个字符)拆分,拆分点选在达到字符数后的下一个空白处
  • 文本拆分规则2:遇到句子结尾符(!.?,且后面是空白或文本结尾)时,立即结束当前片段,不受字符长度限制

改进后的正则表达式

\S.*?[!.?](?= |$)|\S.{0,14}(?= |$)

正则说明

  • 第一个分支 \S.*?[!.?](?= |$):优先匹配从非空白字符开始,直到句子结尾符(!.?)的内容,确保遇到句子结尾就立即拆分,不会把下一句开头的内容包含进来
  • 第二个分支 \S.{0,14}(?= |$):当没有遇到句子结尾时,沿用原规则——从非空白字符开始,匹配最多14个字符(包含开头的非空白),直到下一个空白字符或文本结尾

示例验证

输入文本:

When done correctly, heat exposure offers tremendous benefits. However, it is extremely dangerous to use temperatures that are too hot. What is too hot? That will depend.

拆分后得到的片段:

  • When done correctly, heat exposure offers tremendous benefits.
  • However, it is extremely
  • dangerous to use temperatures
  • that are too hot.
  • What is too hot?
  • That will depend.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:54:51