python - 正则表达式匹配Python中句子中每个单词的最小长度
问题描述
我想写一个正则表达式,它检查句子中每个单词的True
长度,如果所有单词的长度至少为 3,则返回。另外,整个句子只能是小写字母。例如,对于字符串“hello world”,它必须返回真结果,而对于字符串“hi world”,它必须返回假结果。
以下正则表达式无法按预期工作,它给出了True
.
bool(re.compile('([az\s]{3,})+$').match("hi world")))
解决方案
我认为您不需要正则表达式。您可以执行以下操作:
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())
推荐阅读
- kubernetes - fabric8 kubernetes 客户端观察 vs SharedIndexInformer
- java - 递归期间出现错误“线程“主”java.lang.StackOverflowError 中的异常”
- html - 用悬停将圆形照片分成四部分
- c# - SharePoint 2013 CSOM 请求超时
- python - pandas sqrt 和 root 不起作用并产生 NaN
- pagination - HUGO 如何在条款页面中使用分页?
- python - Python 的 cv2 凸缺陷距离太大?
- python - Python datetime 模块和获取当前时间
- aws-cdk - 如何在 CDK 管道中运行数据库迁移
- javascript - 按出现次数升序对元素数组进行排序