1 min read

Python Re Module (Regular Expressions)

The re module provides regular expression matching operations similar to those found in Perl. Regular expressions are a powerful tool for various kinds of string manipulation.

Importing the Module

import re

Basic Patterns

  • .: Matches any character except a newline.
  • ^: Matches the start of the string.
  • $: Matches the end of the string.
  • *: Matches 0 or more repetitions.
  • +: Matches 1 or more repetitions.
  • \d: Matches any decimal digit.
  • \w: Matches any alphanumeric character.

Searching and Matching

Scans through the string looking for the first location where the regular expression pattern produces a match.

import re

text = "The rain in Spain"
x = re.search(r"\bS\w+", text)
print(x.group()) # Output: Spain

re.match()

Checks for a match only at the beginning of the string.

x = re.match(r"The", text) # Matches
y = re.match(r"rain", text) # None (not at start)

re.findall()

Returns all non-overlapping matches of pattern in string, as a list of strings.

text = "The rain in Spain"
x = re.findall(r"ai", text)
print(x) # Output: ['ai', 'ai']

Substitution

re.sub()

Replaces one or many matches with a string.

import re

text = "The rain in Spain"
# Replace white space with 9
x = re.sub(r"\s", "9", text)
print(x) # Output: The9rain9in9Spain

programming/python/python