使用正则表达式查找长度为4的单词

时间:2015-04-17 03:04:04

标签: python regex python-3.x

我试图在长度为4的正则表达式中找到单词

我正在尝试这个,但我得到一个空列表:

#words that have length of 4
s = input("please enter an expression: ")
print(re.findall(r'/^[a-zA-Z]{4}$/',s))

我的代码出了什么问题?

我的输入是:here we are having fun these days

我的预期输出:['here', 'days']

我的输出:[]

2 个答案:

答案 0 :(得分:8)

使用字边界\b。当您在正则表达式^[a-zA-Z]{4}$中添加锚点时,这将匹配只有四个字母的行。它不会检查每个单词。 ^声称我们处在起点,$声称我们已经结束了。 \b匹配单词字符和非单词字符(反之亦然)。因此它匹配单词的一个单词或结尾(零宽度)的开头(零宽度)。

>>> s = "here we are having fun these days"
>>> re.findall(r'\b[a-zA-Z]{4}\b', s)
['here', 'days']

答案 1 :(得分:0)

不需要(可能)复杂的,你可以使用列表理解:

>>> s = "here we are having fun these days"
>>> [word for word in s.split() if len(word) == 4 and word.isalpha()]
['here', 'days']
>>> 
相关问题