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

为何re.compile.findall无法匹配开头的"um"?与re.findall结果差异疑问

问题原因及解决办法

核心问题是你搞混了两种findall方法的参数签名:

  • 顶层的re.findall函数参数顺序是:re.findall(pattern, string, flags=0),第三个参数才是匹配标志(比如re.IGNORECASE)。
  • 而用re.compile生成的正则对象的findall方法,参数顺序是:regex.findall(string, pos=0, endpos=len(string)),第二个参数是匹配的起始位置,不是flags!

你传的re.IGNORECASE数值是2,所以调用re.compile(r"\bum\b").findall(s, re.IGNORECASE)时,相当于从字符串s="um"的索引2位置开始匹配——但这个字符串总长度才2,索引2已经超出范围了,自然返回空列表。

当你用"foobar " + s时,字符串长度是10,从索引2开始匹配,后面的"um"还在范围内,所以能匹配到。

正确用法

想要忽略大小写的匹配,有两种正确方式:

  1. 在compile时就传入flags:
s = "um"
pattern = re.compile(r"\bum\b", re.IGNORECASE)
print(pattern.findall(s))  # 输出 ['um']
  1. 直接用顶层re.findall并传入flags(就是你第一次成功的写法):
print(re.findall(r"\bum\b", s, re.IGNORECASE))  # 输出 ['um']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:02:39