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

如何修复Safari兼容正则表达式,避免误拆分带缩写/引号的句子

兼容Safari的句子拆分正则修复方案

你使用的正则表达式 ((?:[A-Z][a-z]\.|\w\.\w.|.)*?(?:[.!?]|$))(?:\s+|$) 在处理带句点的缩写/首字母缩写、以及引号结尾的句子时会出现误拆分问题,且由于Safari不支持负向后查找,无法借助该特性解决问题。

测试场景

测试字符串

"It was not a good translation because, according to Dr. Giles, "[I]t contains a great deal that Sun Tzŭ did not write, and very little indeed of what he did." The first translation into English was published in 1905 in Tokyo by Capt. E. F. Calthrop, R.F.A. However, this translation is"

当前错误拆分结果

  • "It was not a good translation because, according to Dr. Giles, "[I]t contains a great deal that Sun Tzŭ did not write, and very little indeed of what he did." The first translation into English was published in 1905 in Tokyo by Capt."
  • "E."
  • "F."
  • "Calthrop, R.F.A."
  • "However, this translation is"

预期输出

1: "It was not a good translation because, according to Dr. Giles, "[I]t contains a great deal that Sun Tzŭ did not write, and very little indeed of what he did.""
2: "The first translation into English was published in 1905 in Tokyo by Capt. E. F. Calthrop, R.F.A."
3: "However, this translation is"

修复后的正则表达式

((?:[A-Z][a-z]+\.|[A-Z]\.\s*[A-Z]\.|[A-Z]\.|[a-z]+\.|.)*?(?:[.!?](?:"|')?|$))(?:\s+|$)

修复逻辑

这个正则通过优先匹配常见的缩写模式,避免提前拆分句子,同时兼容Safari的限制:

  • [A-Z][a-z]+\.:匹配 Dr.、Capt. 这类带完整单词的缩写
  • [A-Z]\.\s*[A-Z]\.:匹配 E. F. 这类连续的首字母缩写组合
  • [A-Z]\.:匹配单个首字母缩写(如 E.)
  • [a-z]+\.:可匹配小写单词缩写(如 etc.)
  • [.!?](?:"|')?:匹配句子结尾标点,同时允许标点后紧跟引号,解决引号结尾句子的拆分问题

调整后无需依赖负向后查找,既能正确处理你遇到的边缘案例,又保持了Safari兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:55:41