How to compare two strings using regex in Python?

Comparing two strings using regex in Python allows you to find patterns, match substrings, or perform flexible string comparisons. The re module provides powerful functions like search(), match(), and findall() for string comparison operations.

Basic String Comparison with re.search()

The re.search() function checks if one string exists as a substring in another ?

import re

s1 = 'Pink Forest'
s2 = 'Pink Forrest'

if re.search(s1, s2):
    print('Strings match')
else:
    print('Strings do not match')
Strings do not match

Using re.match() for Pattern Matching

The re.match() function checks if a pattern matches from the beginning of the string ?

import re

pattern = r'^Pink.*'
text = 'Pink Forest'

if re.match(pattern, text):
    print('Pattern matches at the beginning')
else:
    print('Pattern does not match')
Pattern matches at the beginning

Flexible Comparison with Regex Patterns

You can use regex patterns to compare strings with variations in spelling or format ?

import re

# Allow for optional extra 'r' in 'Forest'
pattern = r'Pink Forr?est'
text1 = 'Pink Forest'
text2 = 'Pink Forrest'

for text in [text1, text2]:
    if re.search(pattern, text):
        print(f'"{text}" matches the pattern')
    else:
        print(f'"{text}" does not match')
"Pink Forest" matches the pattern
"Pink Forrest" matches the pattern

Case-Insensitive Comparison

Use the re.IGNORECASE flag for case-insensitive string comparison ?

import re

pattern = 'pink forest'
text = 'PINK FOREST'

if re.search(pattern, text, re.IGNORECASE):
    print('Strings match (case-insensitive)')
else:
    print('Strings do not match')
Strings match (case-insensitive)

Comparison Methods

Method Purpose Match Location
re.search() Find pattern anywhere Entire string
re.match() Match from start Beginning only
re.fullmatch() Exact match Entire string

Conclusion

Use re.search() for substring matching, re.match() for prefix matching, and regex patterns with flags for flexible string comparisons. The re module provides powerful tools for comparing strings with complex patterns.

Updated on: 2026-03-24T19:35:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements