Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.compile: unsupported operand type(s) for &: str and int

Tags:

python

regex

I have following code:

import re
r = re.compile('^[0-9 ]{1,4}Ty', 'i')

I get unexpected error:

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'

How to fix it?

like image 656
Croll Avatar asked Feb 09 '23 02:02

Croll


1 Answers

'i' is not a valid flag value, because all compilation flags used by re functions must be integers (re uses bitwise operations to manipulate flags).

Use re.I (or re.IGNORECASE) instead

import re
r = re.compile('^[0-9 ]{1,4}Ty', re.I)

Technically you can specify flags as strings but in this case they'll have to be included in the pattern:

import re
r = re.compile('(?i)^[0-9 ]{1,4}Ty')

From the 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.

So (?i) has the same effect as passing re.I (or re.IGNORECASE) to compile.

like image 155
vaultah Avatar answered Feb 13 '23 21:02

vaultah