在python re.findall中使用多个标志

Pav*_*van 13 python regex python-2.7

我想在re.findall函数中使用多个标志.更具体地说,我想同时使用IGNORECASEDOTALL标志.

x = re.findall(r'CAT.+?END', 'Cat \n eND', (re.I, re.DOTALL))
Run Code Online (Sandbox Code Playgroud)

错误:

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'
Run Code Online (Sandbox Code Playgroud)

有没有办法使用多个标志?

mip*_*adi 39

是的,但你必须将它们组合在一起:

x = re.findall(r'CAT.+?END','Cat \n eND',re.I | re.DOTALL)
Run Code Online (Sandbox Code Playgroud)

  • 我总是鼓励每个人在传递标志时使用“flags=”。如果不这样做,“my_regex.search”和“my_regex.match”会将标志(内部是“int”)解释为“pos”参数。因此,您的意思是执行“my_regex.search(my_str, re.DOTALL)”,但这将被解释为“my_regex.search(my_str, pos=16)”。如果你总是使用 `flags=` ,你会在上面得到一个错误,你会正确地使用 `re.search` 来代替。 (2认同)

hwn*_*wnd 9

有没有办法使用多个标志?

它没有被提及,但您也可以使用内联(?...)修饰符.

x = re.findall(r'(?si)CAT.+?END', 'Cat \n eND')
Run Code Online (Sandbox Code Playgroud)


Kas*_*mvd 8

你不能把标志放在元组中.在标志中使用管道符(OR操作数):

x = re.findall(r'CAT.+?END','Cat \n eND',flags=re.I | re.DOTALL)
Run Code Online (Sandbox Code Playgroud)