如何在re.Compile中使用format() [英] How do I use format() in re.compile

查看:25
本文介绍了如何在re.Compile中使用format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个正则表达式,它命令python返回列表中具有len=2定义的元音序列的项。

>>> chars = "aeiou"
>>> len = 2
>>> regex = re.compile(r"[+{}+]{{len}}",format(chars))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 234, in compile
    return _compile(pattern, flags)
  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)
TypeError: unsupported operand type(s) for &: 'str' and 'int'
>>> 
>>> def funct(regex,list):
...     for item in list:
...         if regex.search(item):
...             print(item)
... 
>>> list = ['avid','Chaos','st','Cy']
>>> 
>>> funct(regex,list)
avid
Chaos
我应该只得到Chaos,而不是avid。我无法理解将len参数输入到re.compile模块。

推荐答案

您对格式的误用与正则表达式无关。似乎最重要的是,您错误地尝试在格式化的同时使用f字符串。其中,您需要为f字符串添加f前缀,并且可以使用句点(而不是逗号)调用方法。

这两个格式化操作可以互换,并且具有明确定义的求值顺序(先是f字符串,然后是格式化方法)。但是,通常最好使用其中一种,而不是两种都使用。否则,事情会变得不必要地复杂。

使用f字符串:

regex = re.compile(f"[{chars}]{{{len}}}")

双花括号被解释为格式字符串中的文字花括号。您需要第三个集合,以指示len是格式化表达式。

使用格式:

regex = re.compile("[{}]{{{}}}".format(chars, len))
regex = re.compile("[{chars}]{{{len}}}".format(chars= chars, len=len))
regex = re.compile("[{0}]{{{len}}}".format(chars, len=len))

同时使用(为了完整性):

regex = re.compile(f"[{{}}]{{{{{len}}}}}".format(chars))
在任何情况下,您的角色类中都不需要+。在方括号中,+与文字加字符匹配。它不是什么神奇的量词。此外,字符类中的重复字符也是毫无意义的冗余。

因为您的字符串中没有任何反斜杠,所以它不需要是原始字符串,也不需要r前缀。

这篇关于如何在re.Compile中使用format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆