2 min read

Python Regular Expressions

Regular expressions (regex) are a powerful tool for matching patterns in text. Python provides support for regular expressions through the built-in re module.

The re Module

To use regular expressions in Python, you need to import the re module.

import re

Common Functions

Searches the string for a match and returns a Match object if there is a match.

txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
  print("YES! We have a match!")
else:
  print("No match")

re.findall()

Returns a list containing all matches.

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

re.split()

Returns a list where the string has been split at each match.

txt = "The rain in Spain"
x = re.split("\s", txt)
print(x) # Output: ['The', 'rain', 'in', 'Spain']

re.sub()

Replaces one or many matches with a string.

txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x) # Output: The9rain9in9Spain

Metacharacters

  • []: A set of characters (e.g., [a-m])
  • \: Signals a special sequence (e.g., \d)
  • .: Any character (except newline character)
  • ^: Starts with
  • $: Ends with
  • *: Zero or more occurrences
  • +: One or more occurrences
  • ?: Zero or one occurrences
  • {}: Exactly the specified number of occurrences
  • |: Either or
  • (): Capture and group

Special Sequences

  • \d: Returns a match where the string contains digits (numbers from 0-9).
  • \w: Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character).
  • \s: Returns a match where the string contains a white space character.

programming/python/python