0
0
PythonHow-ToBeginner · 3 min read

How to Match Pattern in String Using Python: Simple Guide

Use Python's re module to match patterns in strings. The re.match() function checks if the pattern matches at the start of the string, while re.search() looks for the pattern anywhere in the string.
📐

Syntax

Python uses the re module to work with patterns called regular expressions. The main functions to match patterns are:

  • re.match(pattern, string): Checks if the pattern matches at the start of the string.
  • re.search(pattern, string): Searches the whole string for the pattern.

Both return a match object if found, or None if not.

python
import re

# Match pattern at the start
match = re.match(r'hello', 'hello world')

# Search pattern anywhere
search = re.search(r'world', 'hello world')
💻

Example

This example shows how to check if a string starts with 'cat' and if it contains 'dog' anywhere.

python
import re

text = 'cat and dog'

# Check if string starts with 'cat'
start_match = re.match(r'cat', text)

# Check if string contains 'dog'
contains_search = re.search(r'dog', text)

if start_match:
    print('Starts with cat')
else:
    print('Does not start with cat')

if contains_search:
    print('Contains dog')
else:
    print('Does not contain dog')
Output
Starts with cat Contains dog
⚠️

Common Pitfalls

One common mistake is using re.match() expecting it to find the pattern anywhere in the string. It only checks the start. Use re.search() to find patterns anywhere.

Also, forgetting to use raw strings (prefix r) for patterns can cause errors with backslashes.

python
import re

text = 'hello world'

# Wrong: re.match looks only at start
wrong = re.match('world', text)
print('Wrong match:', wrong)

# Right: re.search finds pattern anywhere
right = re.search('world', text)
print('Right search:', right.group() if right else None)
Output
Wrong match: None Right search: world
📊

Quick Reference

FunctionPurposeReturns
re.match(pattern, string)Match pattern at string startMatch object or None
re.search(pattern, string)Search pattern anywhere in stringMatch object or None
match.group()Get matched text from match objectMatched substring
re.findall(pattern, string)Find all matches in stringList of matched substrings

Key Takeaways

Use the re module to match patterns in strings with regular expressions.
re.match() checks only the start of the string; re.search() looks anywhere.
Always use raw strings (r'pattern') to avoid errors with backslashes.
Check if the match object is None before using it to avoid errors.
Use re.findall() to get all occurrences of a pattern in a string.