我有以下代码:
import re
r = re.compile('^[0-9 ]{1,4}Ty', 'i')
我收到意外错误:
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'
如何解决?
请您参考如下方法:
'i' 不是有效的标志值,因为 all compilation flags used by re functions必须是整数(re 使用按位运算来操作标志)。
改用re.I(或re.IGNORECASE)
import re
r = re.compile('^[0-9 ]{1,4}Ty', re.I)
从技术上讲,您可以将标志指定为字符串,但在这种情况下,它们必须包含在模式中:
import re
r = re.compile('(?i)^[0-9 ]{1,4}Ty')
来自docs :
(?aiLmsux)
One or more letters from the set
'a','i','L','m','s','u','x'. The group matches the empty string; the letters set the corresponding flags.
因此 (?i) 与将 re.I(或 re.IGNORECASE)传递给 compile< 具有相同的效果.
