In Python, re.compile() from the re module creates a regex object from a regular expression pattern. This object lets you perform operations like search(), match(), and findall(). In this article, we will understand about re.compile() method.
import re
# Compile the pattern
pattern = re.compile(r'\d+')
# Search for digits in a string
result = pattern.search("I have 3 cats.")
if result:
print(result.group())
Output
3
Table of Content
Syntax of re.compile()
re.compile(pattern, flags=0)
Parameters:
pattern(str):- The regular expression pattern you want to compile.
- Example:
r'\d+'(matches one or more digits).
flags(optional):- Modifiers that change the behavior of the regex.
- Common flags:
re.IGNORECASEorre.I: Ignore case sensitivity.re.MULTILINEorre.M: Allow^and$to match start and end of lines.re.DOTALLorre.S: Allow.to match newline characters.re.VERBOSEorre.X: Allow adding comments and whitespace for better readability.
Without using flags
In this code we are not using flags which is an optional parameter:
import re
# Compile a regex pattern
pattern = re.compile(r'\d{3}-\d{2}-\d{4}')
# Use the compiled pattern to match
text = "My SSN is 123-45-6789."
match = pattern.search(text)
if match:
print(f"Found: {match.group()}")
Output
Found: 123-45-6789
With Using Flags
In this code we are using flags (Modifiers that change the behavior of the regex.)
import re
# Compile a case-insensitive regex
pattern = re.compile(r'hello', re.IGNORECASE)
# Use the compiled pattern
text = "Hello, GeeksforGeeks!"
match = pattern.search(text)
if match:
print(f" {match.group()}")
Output
Hello