Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in flags as an argument to re.compile

Tags:

python

regex

I would like to pass certain flags into a re.compile function based on logic similar to the below. I was wondering whether it's possible to do so.

  flags = ""

  if multiline:
    flags = 're.M'

  if dotall:
    flags = flags + '|re.S'

  if verbose:
    flags = flags + '|re.X'

  if ignorecase:
    flags = flags + '|re.I'

  if uni_code:
    flags = flags + '|re.U'

  regex = re.compile(r'Test Pattern', flags)
like image 698
Unitarihedron Avatar asked May 05 '14 04:05

Unitarihedron


1 Answers

re flags are just numbers. So, we need to binary OR them, like this

flags = 0

if multiline:
  flags = re.M

if dotall:
  flags |= re.S

if verbose:
  flags |= re.X

if ignorecase:
  flags |= re.I

if uni_code:
  flags |= re.U

regex = re.compile(r'Test Pattern', flags)
like image 124
thefourtheye Avatar answered Oct 15 '22 13:10

thefourtheye