Python re.compile:&:str和int不支持的操作数类型

Cro*_*oll 1 python regex

我有以下代码:

import re
r = re.compile('^[0-9 ]{1,4}Ty', 'i')
Run Code Online (Sandbox Code Playgroud)

我得到意外的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/re.py", line 219, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python3.4/re.py", line 275, in _compile
    bypass_cache = flags & DEBUG
TypeError: unsupported operand type(s) for &: 'str' and 'int'
Run Code Online (Sandbox Code Playgroud)

怎么解决?

vau*_*tah 5

'i'不是有效的标志值,因为函数使用的所有编译标志re必须是整数(re使用按位操作来操作标志).

使用re.I(或re.IGNORECASE)代替

import re
r = re.compile('^[0-9 ]{1,4}Ty', re.I)
Run Code Online (Sandbox Code Playgroud)

从技术上讲,您可以将标志指定为字符串,但在这种情况下,它们必须包含在模式中:

import re
r = re.compile('(?i)^[0-9 ]{1,4}Ty')
Run Code Online (Sandbox Code Playgroud)

来自文档:

(?aiLmsux)

从设置一个或多个字母'a','i','L','m','s', 'u','x'.该组匹配空字符串; 字母设置相应的标志.

因此(?i)与传递re.I(或re.IGNORECASE)具有相同的效果compile.