Python Regex Cheat Sheet

Here is a Python Regex Cheat Sheet. Python uses the re module for working with regular expressions:

Using the re Module

import re

Regex Functions

  • re.match(pattern, string)
    • Searches for a match only at the beginning of the string.
  • re.search(pattern, string)
    • Searches for a match anywhere in the string.
  • re.findall(pattern, string)
    • Returns all non-overlapping matches in a string as a list.
  • re.finditer(pattern, string)
    • Returns an iterator over all non-overlapping matches in a string.

Regex Patterns

Basic Patterns

  • . (dot):
    • Matches any character except a newline.
  • *:
    • Matches 0 or more occurrences of the preceding character.
  • +:
    • Matches 1 or more occurrences of the preceding character.
  • ?:
    • Matches 0 or 1 occurrence of the preceding character.

Character Classes

  • [ ]:
    • Defines a character class.
  • [^ ]:
    • Defines a negated character class.

Anchors

  • ^:
    • Matches the start of a string.
  • $:
    • Matches the end of a string.

Quantifiers

  • {n}:
    • Matches exactly n occurrences.
  • {n,}:
    • Matches n or more occurrences.
  • {n,m}:
    • Matches between n and m occurrences.

Escape Characters

  • \:
    • Escapes a special character.

Common Metacharacters

  • \d:
    • Matches any digit (equivalent to [0-9]).
  • \D:
    • Matches any non-digit.
  • \w:
    • Matches any word character (alphanumeric + underscore).
  • \W:
    • Matches any non-word character.
  • \s:
    • Matches any whitespace character.
  • \S:
    • Matches any non-whitespace character.

Examples

1. Email Validation:

pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

2. Extract Dates:

pattern = r'\d{4}-\d{2}-\d{2}'

3. Find Words with ‘ing’:

pattern = r'\b\w+ing\b'

4. Replace Digits:

pattern = r'\d+'

5. Extract Phone Numbers:

pattern = r'\b\d{3}-\d{3}-\d{4}\b'

These examples demonstrate the usage of regular expressions in Python using the re module. Adjust the patterns based on your specific requirements. For more detailed information, refer to the Python re documentation.