简体   繁体   English

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

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

I'm a Python rookie and am trying to match words in sentences that are exactly 3 letters (small or capital) followed by exactly 3 numbers. 我是Python新手,正在尝试匹配正好3个字母(小写或大写)后面紧跟3个数字的句子中的单词。 Here's my code: 这是我的代码:

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

The problem is the ^. 问题是^。 If I remove it, bla123 is matched, but so is blaa123. 如果我删除它,则bla123是匹配的,但是blaa123也是如此。 If I add the ^ to set a word bound, bla123 isn't matched. 如果我添加^以设置单词绑定,则bla123不匹配。 All my research here and elsewhere has yielded the same pattern, starting with ^. 我在这里和其他地方所做的所有研究都产生了相同的模式,从^开始。 Some suggestions were to use \\b as prefix and suffix, but that didn't work for me either. 一些建议是使用\\ b作为前缀和后缀,但这对我也不起作用。

Please help. 请帮忙。 I'm sure there's something I'm overlooking over and over again. 我确定我一遍又一遍地忽略了某些事情。 Thanks! 谢谢!

You can remove the ^ and $ checks, add word boundaries ( \\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