首页 > 解决方案 > 使用正则表达式在末尾匹配带有元音的字符串

问题描述

我正在尝试返回列表中的项目,该列表中的项目末尾的字符串中有四个或更多字符(可以重复)。

字符串是 ="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

标签: regexpython-3.x

解决方案


你需要这样写,

[iaeou]{4,}$

正则表达式中的这部分 '+{4,}' 无效,因为 + 本身是一个量词,而 {4,} 也是一个量词,并且您无法量化正则表达式有效的量词,因此您一定会遇到一些模式错误。如果你真的想量化一个 + 号,你需要像这样逃避它,

\+{1,4}

但根据您的问题,这不是您想要的。希望澄清。


推荐阅读