JavaScript正则表达式:正确识别段落句子端点的方案求助
带缩写的句子分割正则优化方案
我在Stack Overflow上查阅了诸多解决方案,经测试后发现它们都难以完成段落句子端点识别的任务。当前使用的正则表达式/(?<![A-Z]\.)(?<=[.!?;])(?=[ A-Z])/已接近需求,但遇到Mr.、Mrs.这类缩写时会失效。希望实现两种效果:要么提取所有句子,要么按带标点的句子结尾进行分割。
测试字符串
Cool commonly refers to: Cool, a moderately low temperature Cool (aesthetic), an aesthetic of attitude, behavior, and styleCool or COOL may also refer to: Country of origin labelling mCOOL - US consumer legislation to enforce COOL at the grocery store Cool (programming language) COOL, a computer language used in the CLIPS tool Cool, an internal name of C# Cool (Rotterdam), Netherlands Cool, California, U.S. Cool, Texas, U.S. Cool (band), a South Korean K-pop music group Cool jazz Cool (George Duke album) (2000) Lupe Fiasco's The Cool (2007) The Cool (character), the associated concept character Cool (Joyce album) (2015) "Cool" (Alesso song) (2015) "Cool" (Anthony Hamilton song) (2008) "Cool" (Jonas Brothers song) (2019) "Cool" (Le Youth song) (2013) "Cool" (Dua Lipa song) (2020) "Cool" (Gwen Stefani song) (2005) "Cool" (The Time song) (1981), later co 0.0.0.0. (.) vered. By Snoop Dogg and Prince "Cool" (West Side Story song) (1957) Cool (producer), American hip hop producer Fabien Cool (born 1972), French footballer Tré Cool (born 1972), American drummer (Green Day) Wim Cool (born 1943), Dutch politician LL Cool J (born 1968), American rapper CoolTV, a Canadian television channel Cool TV, a U.S. Hungarian television channel "Cool" (Smallville), an episode of Smallville COOL Award, children's book choice award Cool colors, a perc 8.5/10 eptual and psychological classification of colors Cumhall, a figure in Irish mythology Majesco Entertainment' NASDAQ ticker symbol Mr. Cool (Mr. Men), a fictional character in the Mr. Men children's book series Steve McQueen: popularly known as "The King of Cool" Cool Change (disambiguation) Cool Kids (disambiguation) Kool (disambiguation) Mister Cool (disambiguation) All pages with titles beginning with Cool All pages with titles containing Cool. Let's just add some other use cases (here). And "here."
优化后的正则方案
针对缩写导致的分割错误,我们在原正则基础上添加负向预查排除常见头衔缩写,避免在Mr.、Mrs.这类词后误分割句子:
/(?<!(Mr|Mrs|Ms|Dr|Sr|Jr)\.)(?<=[.!?;])(?=[ A-Z])/g
正则逻辑说明
(?<!(Mr|Mrs|Ms|Dr|Sr|Jr)\.):负向预查,排除前面是指定缩写加句号的情况,过滤头衔缩写的干扰(?<=[.!?;]):匹配句子结尾的标点符号(句号、感叹号、问号、分号)(?=[ A-Z]):匹配标点后紧跟空格和大写字母的位置,符合英文句子大写开头的规则
如果需要支持更多缩写,只需在括号内补充对应的缩写即可,例如(?<!(Mr|Mrs|Ms|Dr|Sr|Jr|Prof|Capt)\.)。
两种实现方式
1. 按句子结尾分割字符串
以JavaScript为例,使用split()方法完成分割:
const testStr = '上述测试字符串内容'; const regex = /(?<!(Mr|Mrs|Ms|Dr|Sr|Jr)\.)(?<=[.!?;])(?=[ A-Z])/g; const splitResult = testStr.split(regex); console.log(splitResult);
2. 提取所有完整句子
通过匹配直接提取包含结尾标点的完整句子:
const testStr = '上述测试字符串内容'; const extractRegex = /(.*?(?<!(Mr|Mrs|Ms|Dr|Sr|Jr)\.)[.!?;](?=[ A-Z]|$))/g; const extractedSentences = testStr.match(extractRegex); console.log(extractedSentences);
内容的提问来源于stack exchange,提问作者Daltron
相关产品推荐
相关产品推荐

