Regex Special Characters Cheat Sheet - Catalog Library
Learning

Regex Special Characters Cheat Sheet - Catalog Library

1200 × 1553 px March 1, 2026 Ashley Learning
Download

Mastering regular expressions (regex) in Python can significantly enhance your text processing capabilities. Whether you're a seasoned developer or just starting out, having a comprehensive Python Regex Cheat Sheet at your disposal can save you time and effort. This guide will walk you through the essentials of regex in Python, providing you with a handy reference that you can use in your projects.

Understanding Regular Expressions

Regular expressions are powerful tools for pattern matching and text manipulation. They allow you to search, edit, and manipulate strings based on specific patterns. In Python, the re module provides support for working with regular expressions.

Basic Syntax and Functions

The re module in Python offers a variety of functions to work with regex. Here are some of the most commonly used functions:

  • re.match(): Determines if the regex pattern matches at the beginning of the string.
  • re.search(): Scans through the string, looking for any location where the regex pattern produces a match.
  • re.findall(): Finds all substrings where the regex pattern produces a match and returns them as a list.
  • re.sub(): Replaces occurrences of the regex pattern with a replacement string.
  • re.split(): Splits the string by the occurrences of the regex pattern.

Common Regex Patterns

Understanding common regex patterns is crucial for effective text processing. Here are some essential patterns:

  • .: Matches any single character except a newline.
  • d: Matches any digit (equivalent to [0-9]).
  • D: Matches any non-digit character.
  • w: Matches any word character (equivalent to [a-zA-Z0-9_]).
  • W: Matches any non-word character.
  • s: Matches any whitespace character (spaces, tabs, newlines).
  • S: Matches any non-whitespace character.
  • : Matches a word boundary.
  • B: Matches a non-word boundary.
  • ^: Matches the start of a string.
  • $: Matches the end of a string.
  • *: Matches 0 or more occurrences of the preceding element.
  • +: Matches 1 or more occurrences of the preceding element.
  • ?: Matches 0 or 1 occurrence of the preceding element.
  • {n}: Matches exactly n occurrences of the preceding element.
  • {n,}: Matches n or more occurrences of the preceding element.
  • {n,m}: Matches between n and m occurrences of the preceding element.
  • []: Matches any one of the characters inside the brackets.
  • [^]: Matches any character not in the brackets.
  • |: Acts as a boolean OR operator.
  • (): Groups multiple tokens together and creates a capture group.
  • </code>: Escapes a special character.

Using the Python Regex Cheat Sheet

To make the most of your Python Regex Cheat Sheet, it’s essential to understand how to apply these patterns in your code. Below are some examples to illustrate how to use regex in Python.

Matching Patterns

To match a pattern at the beginning of a string, you can use the re.match() function:

import re

pattern = r’^Hello’ text = ‘Hello, World!’

match = re.match(pattern, text) if match: print(‘Match found:’, match.group()) else: print(‘No match found.’)

To search for a pattern anywhere in the string, use the re.search() function:

pattern = r'World'
text = 'Hello, World!'

match = re.search(pattern, text)
if match:
    print('Match found:', match.group())
else:
    print('No match found.')

💡 Note: The re.match() function only checks the beginning of the string, while re.search() scans the entire string.

Finding All Matches

To find all occurrences of a pattern in a string, use the re.findall() function:

pattern = r’d+’
text = ‘There are 123 apples and 456 oranges.’

matches = re.findall(pattern, text) print(‘Matches found:’, matches)

Replacing Patterns

To replace occurrences of a pattern with a replacement string, use the re.sub() function:

pattern = r’d+’
text = ‘There are 123 apples and 456 oranges.’
replacement = ‘NUMBER’

new_text = re.sub(pattern, replacement, text) print(‘Replaced text:’, new_text)

Splitting Strings

To split a string by occurrences of a pattern, use the re.split() function:

pattern = r’s+’
text = ‘Hello, World! This is a test.’

parts = re.split(pattern, text) print(‘Split parts:’, parts)

Advanced Regex Techniques

Beyond the basics, regex in Python offers advanced techniques for more complex text processing tasks. Here are some advanced patterns and techniques:

Capture Groups

Capture groups allow you to extract specific parts of a matched pattern. Use parentheses () to create capture groups:

pattern = r’(d{4})-(d{2})-(d{2})’
text = ‘The date is 2023-10-05.’

match = re.search(pattern, text) if match: year, month, day = match.groups() print(‘Year:’, year) print(‘Month:’, month) print(‘Day:’, day)

Non-Capturing Groups

Non-capturing groups are used to group patterns without creating a capture group. Use (?: … ) to create a non-capturing group:

pattern = r’(?:d{4})-(d{2})-(d{2})’
text = ‘The date is 2023-10-05.’

match = re.search(pattern, text) if match: month, day = match.groups() print(‘Month:’, month) print(‘Day:’, day)

Lookahead and Lookbehind

Lookahead and lookbehind assertions allow you to match patterns based on what follows or precedes them without including them in the match. Use (?= … ) for lookahead and (?<= … ) for lookbehind:

pattern = r’w+(?=ing)’
text = ‘She is running and jumping.’

matches = re.findall(pattern, text) print(‘Matches found:’, matches)

Named Capture Groups

Named capture groups allow you to assign names to capture groups, making your regex patterns more readable. Use (?P … ) to create a named capture group:

pattern = r’(?Pd{4})-(?Pd{2})-(?Pd{2})’
text = ‘The date is 2023-10-05.’

match = re.search(pattern, text) if match: year = match.group(‘year’) month = match.group(‘month’) day = match.group(‘day’) print(‘Year:’, year) print(‘Month:’, month) print(‘Day:’, day)

Common Use Cases

Regex in Python is incredibly versatile and can be applied to a wide range of use cases. Here are some common scenarios where regex can be particularly useful:

Email Validation

Validating email addresses is a common task that can be efficiently handled with regex:

pattern = r’^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$’
email = ‘example@example.com’

if re.match(pattern, email): print(‘Valid email address.’) else: print(‘Invalid email address.’)

Phone Number Extraction

Extracting phone numbers from text can be done using regex patterns that match common phone number formats:

pattern = r’(d{3}) d{3}-d{4}’
text = ‘Contact us at (123) 456-7890 for more information.’

matches = re.findall(pattern, text) print(‘Phone numbers found:’, matches)

URL Extraction

Extracting URLs from text is another common use case for regex:

pattern = r’https?://[^s/$.?#].[^s]*’
text = ‘Visit our website at https://www.example.com for more details.’

matches = re.findall(pattern, text) print(‘URLs found:’, matches)

Data Cleaning

Regex can be used to clean and preprocess text data by removing unwanted characters or patterns:

pattern = r’[^a-zA-Z0-9s]’
text = ‘Hello, World! This is a test…’

cleaned_text = re.sub(pattern, “, text) print(‘Cleaned text:’, cleaned_text)

Best Practices

To make the most of your Python Regex Cheat Sheet, follow these best practices:

  • Keep your regex patterns as simple as possible to improve readability and performance.
  • Use raw strings (r”) for regex patterns to avoid issues with escape characters.
  • Test your regex patterns thoroughly to ensure they work as expected.
  • Use named capture groups for better readability and maintainability.
  • Consider using regex libraries or tools for complex patterns to simplify development.

By following these best practices, you can write more efficient and maintainable regex patterns in Python.

💡 Note: Always test your regex patterns with a variety of input data to ensure they handle edge cases and unexpected inputs.

Conclusion

Mastering regex in Python can significantly enhance your text processing capabilities. With a comprehensive Python Regex Cheat Sheet, you can quickly reference essential patterns and functions, making your development process more efficient. Whether you’re validating email addresses, extracting phone numbers, or cleaning data, regex provides a powerful toolset for handling text data. By understanding the basics and advanced techniques, you can leverage regex to solve a wide range of text processing challenges in your Python projects.

Related Terms:

  • python regex pdf
  • python regex functions
  • regex python cheatsheet
  • python regex cheat sheet examples
  • python regex table
  • python regex example