regex - 使用正则表达式在末尾匹配带有元音的字符串
问题描述
我正在尝试返回列表中的项目,该列表中的项目末尾的字符串中有四个或更多字符(可以重复)。
字符串是 ="iaeou"
我写
"[iaeou]+{4,}$"
这不是返回我想要的,我想知道它有什么问题。
我收到错误“多次重复”。
>>> example = ['ti','tii','ta','tae','taeguu','fy']
>>> import re
>>> for item in example:
... if re.search("[iaeou]+{4,}$",item):
... print(item)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 286, in _compile
p = sre_compile.compile(pattern, flags)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 930, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 426, in _parse_sub
not nested and not items))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 654, in _parse
source.tell() - here + len(this))
re.error: multiple repeat at position 8
解决方案
你需要这样写,
[iaeou]{4,}$
正则表达式中的这部分 '+{4,}' 无效,因为 + 本身是一个量词,而 {4,} 也是一个量词,并且您无法量化正则表达式有效的量词,因此您一定会遇到一些模式错误。如果你真的想量化一个 + 号,你需要像这样逃避它,
\+{1,4}
但根据您的问题,这不是您想要的。希望澄清。
推荐阅读
- javascript - JS 计算器不能在 wordpress 中工作,脚本在旧网站上工作
- python - 全局变量不跨 FUNCTIONS
- bamboo - 有没有办法在 Bamboo 中为所有拉取请求和一组自定义分支创建计划分支
- c# - 登录后 ASP.NET Identity 用户为空
- java - 如何使用 Java 在 Azure 服务总线中创建队列?
- ssl - 在 gRPC TLS 中禁用证书检查
- xcode - Xcode:当应用程序在模拟器中崩溃或启用调试时,如何保持 IB 和 Assistant 编辑器打开
- c++ - 在 Visual Studio 中停止运行程序时终止
- excel - 根据下拉列表选择用其他表中的数据填充空表
- javascript - 如何将 ImageData 写入 HTML5 画布上下文?