Pass re.IGNORECASE to the flags param of search, match, or sub:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
Answer from Michael Haren on Stack Overflowpython - Case insensitive regular expression without re.compile? - Stack Overflow
python - Case insensitive replace - Stack Overflow
python - Issue with case-insensitive regex pattern for re.sub() - Stack Overflow
python - Why doesn't ignorecase flag (re.I) work in re.sub() - Stack Overflow
Pass re.IGNORECASE to the flags param of search, match, or sub:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
Seems to me that you should be doing:
import re
print(re.sub('class', 'function', 'Class object', flags=re.I))
Without this, the re.I argument is passed to the count argument.
The flags argument is the fifth one - you're passing the value of re.I as the count argument (an easy mistake to make).
You can supply the flag re.IGNORECASE to functions in the re module as described in the docs.
matcher = re.compile(myExpression, re.IGNORECASE)
Using re is the best solution even if you think it's complicated.
To replace all occurrences of 'abc', 'ABC', 'Abc', etc., with 'Python', say:
re.sub(r'(?i)abc', 'Python', a)
Example session:
>>> a = 'abc asd Abc asd ABCDE XXAbCXX'
>>> import re
>>> re.sub(r'(?i)abc', 'Python', a)
'Python asd Python asd PythonDE XXPythonXX'
>>>
Note how embedding (?i) at the start of the regexp makes it case insensitive. Also note the r'...' string literal for the regexp (which in this specific case is redundant but helps as soon as you use a regexp that has backslashes (\) in them.
What am I missing here? I am doing a re.sub() call with re.IGNORECASE, but it is clearly NOT ignoring the case :/
import re
for txt in ["This is line 1.", "This is LINE 2."]:
print(re.sub(rf"(\W)(line)(\W)", r"\1<\2>\3", txt, re.I))The output of the above is
This is <line> 1. This is LINE 2.
As you can see, re.sub() appears to be case-sensitive, even though I have the flag re.I. I tried compiling the expression and got the same results.
Any feedback is greatly appreciated. Thank you