繁体   English   中英

对使用正则表达式精确匹配3个字母和紧随其后的3个数字感到困惑

[英]Puzzled about use of regex to match exactly 3 letters followed by exactly 3 numbers

我是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也是如此。 如果我添加^以设置单词绑定,则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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM