Using more than one flag in python re.findall

PythonRegexPython Re

Python Problem Overview


I would like to use more than one flag with the re.findall function. More specifically, I would like to use the IGNORECASE and DOTALL flags at the same time.

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

Error :

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'

Is there a way to use more than one flag ?

Python Solutions


Solution 1 - Python

Yes, but you have to OR them together:

x = re.findall(pattern=r'CAT.+?END', string='Cat \n eND', flags=re.I | re.DOTALL)

Solution 2 - Python

You can't put the flags within a tuple. Use the pipe character (OR operand) within your flags:

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

Solution 3 - Python

>Is there a way to use more than one flag ?

It wasn't mentioned, but you can use inline (?...) modifiers as well.

x = re.findall(r'(?si)CAT.+?END', 'Cat \n eND')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavanView Question on Stackoverflow
Solution 1 - PythonmipadiView Answer on Stackoverflow
Solution 2 - PythonMazdakView Answer on Stackoverflow
Solution 3 - PythonhwndView Answer on Stackoverflow