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

Python正则表达式求助:匹配含asked的头衔开头句子失败

问题解决与修正方案

原正则的问题分析

  1. 首尾锚点错误:原正则用^和$锚定整个文本的首尾,但目标句子是文本中的子句而非整个文本,导致完全匹配不到内容。
  2. 匹配逻辑缺陷:(.|\n)未开启re.DOTALL模式时,.无法匹配换行符;且该写法不如[\s\S]简洁高效,后者可覆盖所有字符(包括换行)。
  3. 未覆盖开头空白:部分目标句子前存在空白字符(比如第三个句子前的两个空格),原正则未处理这种场景。
  4. 贪婪匹配风险:{1,}是贪婪匹配规则,可能跨多个句子抓取内容,导致结果不符合预期。

修正后的代码

import re

text_list = "26 Mr Kwek Hian Chuan Henry asked the Minister for the Environment and Water Resources whether Singapore will stay the course on fighting climate change and meet our climate change commitments despite the current upheavals in the energy market and the potential long-term economic impact arising from the COVID-19 situation. We agree with the Panel and will instead strengthen regulations to safeguard the safety of path users. With regard to Ms Rahayu Mahzam's suggestion of tapping on the Small Claims Tribunal for personal injury claims up to $20,000, we understand that the Tribunal does not hear personal injury claims.  Mr Gan Thiam Poh, Ms Rahayu Mahzam and Mr Melvin Yong have asked about online retailers of PMDs. Mr Melvin Yong asked about the qualifications and training of OEOs."

# 修正后的正则表达式
asked_regex = re.compile(r'\s*(Mr|Miss|Ms|Dr)\s+[\s\S]*?asked[\s\S]*?\.', re.MULTILINE)
# 提取结果并整理格式
asked = [sentence.strip() + '.' for sentence in re.findall(asked_regex, text_list)]

print(asked)

正则规则说明

  • \s*:匹配句子开头可能存在的任意空白字符(空格、制表符等)
  • (Mr|Miss|Ms|Dr):精准匹配指定头衔
  • \s+:匹配头衔后的至少一个空格,确保头衔与姓名分隔开
  • [\s\S]*?:非贪婪匹配任意字符(含换行),避免跨句子抓取
  • asked:匹配目标关键词
  • [\s\S]*?\.:非贪婪匹配到句末的句号
  • re.MULTILINE:适配文本中任意位置的句子匹配场景

最终中文结果

["郭贤川·亨利先生询问环境及水源部长,尽管当前能源市场动荡以及新冠疫情带来的潜在长期经济影响,新加坡是否会坚持应对气候变化的路线并履行相关承诺。",
"陈添宝先生、拉哈尤·马扎姆女士和梅尔文·杨先生询问了电动代步工具在线零售商的相关问题。",
"梅尔文·杨先生询问了OEO的资质与培训相关问题。"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:33:38