【发布时间】:2015-08-19 12:04:50
【问题描述】:
我想在re.findall 函数中使用多个标志。更具体地说,我想同时使用IGNORECASE 和DOTALL 标志。
x = re.findall(r'CAT.+?END', 'Cat \n eND', (re.I, re.DOTALL))
错误:
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
x = re.findall(r'CAT.+?END','Cat \n eND',(re.I,re.DOTALL))
File "C:\Python27\lib\re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
File "C:\Python27\lib\re.py", line 243, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Python27\lib\sre_compile.py", line 500, in compile
p = sre_parse.parse(p, flags)
File "C:\Python27\lib\sre_parse.py", line 673, in parse
p = _parse_sub(source, pattern, 0)
File "C:\Python27\lib\sre_parse.py", line 308, in _parse_sub
itemsappend(_parse(source, state))
File "C:\Python27\lib\sre_parse.py", line 401, in _parse
if state.flags & SRE_FLAG_VERBOSE:
TypeError: unsupported operand type(s) for &: 'tuple' and 'int'
有没有办法使用多个标志?
【问题讨论】:
-
查看re.compile的文档。
-
除了@PeterWood的链接:docs.python.org/2.7/howto/regex.html#compilation-flags
-
如果你使用很多正则表达式,如果可以的话,最好使用内联修饰符。主要是因为您实际上并未将
FLAGS与 FindAll 函数一起使用,它们被传递并附加到正则表达式对象。修饰符绑定到正则表达式对象,而不是正则表达式使用函数。因此,如果您在其他地方剪切并粘贴正则表达式,您根本不必担心标志。所以,r'(?si)CAT.+?END'是最好的方法。 -
@PeterWood,3.8.1 的文档对这个问题没用。
-
@ZachYoung 我在 5 1/2 年前回答了这个问题。