kyrenia kyrenia - 3 years ago 195
Python Question

Case-insensitive replacement in Python using regex not working

I can't work out why my regex is not working case-instentitively, despite having the

flag set. For example:

re.sub(r"Item", "success", "ITEM", re.IGNORECASE)

I would have thought would have made the substitution to
, but instead it remains as the prior term.

For reference, I am aware that the following alteration will work, but just unsure why it wasn't working with my original code:

re.sub(r"(?i)Item", "success", "ITEM")

Answer Source

You need to pass it as flags keyword argument :

>>> re.sub(r"Item", "success", "ITEM",  flags=re.IGNORECASE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download