如何在 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-string,然后是格式方法(。但是,通常最好使用其中之一,而不是同时使用两者。否则事情会变得不必要地复杂。

使用 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前缀。

可以通过在字符串文本的引号前添加f来使用 f 字符串,以便可以在len两边使用一对大括号来计算其作为字符串一部分的值,并使用.(而不是,(调用字符串的format方法。但是,由于 f 字符串在传递给str.format进行格式化之前首先进行评估,因此为了使空的大括号{}由 f 字符串解析器逐字保留,您必须使用双大括号来转义它们。但是,由于您需要在len的值周围使用大括号才能使其成为正则表达式中的量词,因此您需要再次通过将它们加倍来转义它们,以便str.format保留大括号:

regex = re.compile(fr"[+{{}}+]{{{{{len}}}}}".format(chars))

由于大括号在所有 f 字符串、str.format和正则表达式中都有特殊含义,因此我建议您使用字符串格式运算符%来格式化字符串,这样您就不必处理上面的逃逸地狱:

regex = re.compile(r'[+%s+]{%d}' % (chars, len))

相关内容

最新更新