首页 > 解决方案 > 正则表达式匹配Python中句子中每个单词的最小长度

问题描述

我想写一个正则表达式,它检查句子中每个单词的True长度,如果所有单词的长度至少为 3,则返回。另外,整个句子只能是小写字母。例如,对于字符串“hello world”,它必须返回真结果,而对于字符串“hi world”,它必须返回假结果。

以下正则表达式无法按预期工作,它给出了True.

bool(re.compile('([az\s]{3,})+$').match("hi world")))

标签: pythonregex

解决方案


我认为您不需要正则表达式。您可以执行以下操作:

s = 'this is a sentence of some sort'
words = s.split()
test = [w for w in words if len(w) > 3]
print(len(test) == len(words)) # False

或等效地:

s = 'this is a sentence of some sort'
words = s.split()
acceptable = lambda x: len(x) > 3
print(len(words) == len(list(filter(acceptable, words))))

甚至:

s = 'this is a sentence of some sort'
words = s.split()
res = all(len(word) > 3 for word in words)
print(res)

或者,正如@pault 建议的那样:

s = 'this is a sentence of some sort'
all(len(w) > 3 and w.islower() for w in s.split())

推荐阅读