Use re.compile() Method in Python Regular Expressions



Python's re.compile() function is a powerful tool for developing regular expression (regex) patterns. It allows you to pre-compile and save patterns to easily enhance the speed of your code by eliminating the need to recompile the patterns multiple times.

Pattern Matching in Python with Regex

This efficient pattern-handling approach uses the 're' module for regular expressions and allows pattern matching. This solution is especially useful in scenarios that require frequent pattern matching, making your code more optimized.

Example

This example shows how compiling a pattern can improve performance when searching through text.

import re
pattern=re.compile('TP')
result=pattern.findall('TP Tutorialspoint TP')
print (result)
result2=pattern.findall('TP is most popular tutorials site of India')
print (result2)

Output

Following is the output of the above code ?

['TP', 'TP']
['TP']

Case-Insensitive Matching Using re.IGNORECASE.

The re.IGNORECASE flag allows matching patterns regardless of their case (uppercase or lowercase). It treats 'A' and 'a' as the same character.

Example

In this example, we will compile a regex pattern to perform case-insensitive matching for a specific word in a text using re.IGNORECASE flag.

import re

case_insensitive_pattern = re.compile(r'tutorial', re.IGNORECASE)

text5 = "Welcome to Tutorial on Python Regular Expressions."
text6 = "This is a tutorial for beginners. Make sure to check out the TUTORIAL section!"

# Find all occurrences of 'tutorial', regardless of case
matches1 = case_insensitive_pattern.findall(text5)
print(matches1)  

matches2 = case_insensitive_pattern.findall(text6)
print(matches2)  

Output

Following is the output of the above code ?

['Tutorial']
['tutorial', 'TUTORIAL']

Substituting Text Using the sub() Method

The 'sub()' method helps you find and replace specific patterns in text. You can choose what to replace each match with, making it easy to change the text.

Example

In this example, we will compile a regex pattern to find and replace specific words in a text with another word.

import re

# Compile the regex pattern for matching the word 'bad'
bad_word_pattern = re.compile(r'\bbad\b', re.IGNORECASE)
text7 = "This is a bad example of a bad practice. Avoid bad habits!"

# Substitute 'bad' with 'good' in the text
modified_text = bad_word_pattern.sub('good', text7)
print(modified_text)

Output

Following is the output of the above code ?

This is a good example of a good practice. Avoid good habits!
Updated on: 2025-01-24T13:09:29+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements