Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a case insensitive Python regular expression without re.compile?
By default, Python regular expressions (regex) look for case-sensitive matches. The terms "apple" and "Apple" are treated as different patterns. However, we can perform case-insensitive matching by using the re.IGNORECASE flag directly in regex functions without needing re.compile().
Basic Syntax
To make any regex function case-insensitive, add the flags=re.IGNORECASE parameter ?
re.function(pattern, string, flags=re.IGNORECASE)
This works with re.search(), re.match(), re.findall(), re.sub(), and other regex functions.
Using re.findall() with Case Insensitivity
Let's find all occurrences of "python" regardless of case ?
import re text = "Python is a versatile programming language. python rocks!" matches = re.findall(r"python", text, re.IGNORECASE) print(matches)
['Python', 'python']
The function finds both "Python" and "python" because we used the re.IGNORECASE flag.
Using re.search() for Case Insensitive Matching
The re.search() function finds the first occurrence of a pattern ?
import re
text = "Learning Python can be fun."
match = re.search(r"learning", text, re.IGNORECASE)
if match:
print(f"Found: '{match.group()}' at position {match.start()}")
else:
print("Not found")
Found: 'Learning' at position 0
The function successfully matches "Learning" even though our pattern was lowercase "learning".
Using re.sub() for Case Insensitive Replacement
Replace text patterns regardless of case using re.sub() ?
import re text = "Python is GREAT for data science. Great choice!" new_text = re.sub(r"great", "fantastic", text, flags=re.IGNORECASE) print(new_text)
Python is fantastic for data science. fantastic choice!
Both "GREAT" and "Great" are replaced with "fantastic" because of the case-insensitive flag.
Multiple Patterns Example
You can combine multiple patterns with case insensitivity ?
import re
text = "I love PYTHON and Java programming"
languages = re.findall(r"python|java", text, re.IGNORECASE)
print(f"Found languages: {languages}")
Found languages: ['PYTHON', 'Java']
Comparison of Methods
| Function | Purpose | Returns |
|---|---|---|
re.findall() |
Find all matches | List of strings |
re.search() |
Find first match | Match object or None |
re.sub() |
Replace matches | Modified string |
Conclusion
Use flags=re.IGNORECASE with any regex function to perform case-insensitive matching without re.compile(). This approach is simple and works with re.search(), re.findall(), re.sub(), and other regex functions for flexible pattern matching.
