Skip to main content
 首页 » 编程设计

python之对使用正则表达式精确匹配后跟 3 个数字的 3 个字母感到困惑

2025年05月04日33虾米姐

我是一名 Python 菜鸟,我正在尝试匹配句子中恰好有 3 个字母(小写字母或大写字母)后跟恰好 3 个数字的单词。这是我的代码:

def regex(): 
    pattern = r'^[a-zA-Z]{3}\d{3}$' 
    found = re.search(pattern, "My word is bla123") 
    print(found) 

问题是^。如果我删除它,bla123 匹配,但 blaa123 也匹配。如果我添加 ^ 来设置单词绑定(bind),则 bla123 不匹配。我在这里和其他地方的所有研究都产生了相同的模式,从 ^ 开始。一些建议是使用\b 作为前缀和后缀,但这对我也不起作用。

请帮忙。我确定有些事情我一遍又一遍地忽略了。谢谢!

请您参考如下方法:

您可以删除^ 和$ 检查,添加单词边界(\b):

>>> pattern = r'\b[a-zA-Z]{3}\d{3}\b' 
>>> re.findall(pattern, "My word is bla123") 
['bla123'] 
>>> re.findall(pattern, "My word345 is bla123") 
['bla123'] 
>>> re.findall(pattern, "My word345 and bla56 is bla123 and abc343") 
['bla123', 'abc343']