List of Basic Regular Expression Patterns in Python

Complete List of Basic Regular Expression Patterns in Python

Character Classes

PatternDescriptionExample
[abc]Matches any one of the characters a, b, or c[aeiou] matches any vowel
[^abc]Matches any character except a, b, or c[^0-9] matches non-digits
[a-z]Matches any character in range a to z[a-z] matches lowercase letters
[A-Z]Matches any character in range A to Z[A-Z] matches uppercase letters
[0-9]Matches any digit[0-9] matches digits 0-9
[a-zA-Z]Matches any letter[a-zA-Z] matches all letters
[a-zA-Z0-9_]Equivalent to \wMatches word characters

Predefined Character Classes

PatternDescriptionEquivalent
.Matches any character except newline
\dMatches any digit[0-9]
\DMatches any non-digit[^0-9]
\wMatches any word character[a-zA-Z0-9_]
\WMatches any non-word character[^a-zA-Z0-9_]
\sMatches any whitespace character[ \t\n\r\f\v]
\SMatches any non-whitespace character[^ \t\n\r\f\v]

Anchors (Position Matchers)

PatternDescriptionExample
^Matches start of string (or line with re.MULTILINE)^Hello matches “Hello” at start
$Matches end of string (or line with re.MULTILINE)world$ matches “world” at end
\bMatches word boundary\bword\b matches “word” as whole word
\BMatches non-word boundary\Bword\B matches “word” inside other words

Quantifiers (Repetition)

PatternDescriptionExample
*0 or more occurrencesa* matches “”, “a”, “aa”, “aaa”, …
+1 or more occurrencesa+ matches “a”, “aa”, “aaa”, …
?0 or 1 occurrencea? matches “” or “a”
{n}Exactly n occurrencesa{3} matches “aaa”
{n,}n or more occurrencesa{2,} matches “aa”, “aaa”, “aaaa”, …
{n,m}Between n and m occurrencesa{2,4} matches “aa”, “aaa”, “aaaa”

Alternation and Grouping

PatternDescriptionExample
``OR operator (alternation)`catdog` matches “cat” or “dog”
()Grouping and capturing(abc)+ matches “abc”, “abcabc”, etc.
(?:)Non-capturing group(?:abc)+ groups without capturing

Escape Sequences

PatternDescriptionExample
\\Backslash\\ matches “”
\.Literal dot\. matches “.”
\*Literal asterisk\* matches “*”
\+Literal plus\+ matches “+”
\?Literal question mark\? matches “?”
\(Literal opening parenthesis\( matches “(“
\)Literal closing parenthesis\) matches “)”
\[Literal opening bracket\[ matches “[“
\]Literal closing bracket\] matches “]”
\{Literal opening brace\{ matches “{“
\}Literal closing brace\} matches “}”
\^Literal caret\^ matches “^”
\$Literal dollar\$ matches “$”
|Literal pipe| matches “

Special Sequences

PatternDescriptionExample
\AMatches only at start of string\AStart
\ZMatches only at end of stringend\Z
\nNewline character
\tTab character
\rCarriage return
\fForm feed
\vVertical tab

Practical Examples with Each Pattern Type

python

import re

# Character Classes
text = "abc123XYZ"
print(re.findall(r'[a-z]', text))        # ['a', 'b', 'c']
print(re.findall(r'[^0-9]', text))       # ['a', 'b', 'c', 'X', 'Y', 'Z']

# Predefined Classes
text = "Hello 123 World!"
print(re.findall(r'\d', text))           # ['1', '2', '3']
print(re.findall(r'\w', text))           # ['H', 'e', 'l', 'l', 'o', '1', '2', '3', 'W', 'o', 'r', 'l', 'd']

# Anchors
text = "Hello world\nHello python"
print(re.findall(r'^Hello', text))       # ['Hello'] (start of string)
print(re.findall(r'^Hello', text, re.MULTILINE))  # ['Hello', 'Hello'] (start of each line)

# Quantifiers
text = "a aa aaa aaaa"
print(re.findall(r'a{2,3}', text))       # ['aa', 'aaa', 'aaa']

# Alternation
text = "I have a cat and a dog"
print(re.findall(r'cat|dog', text))      # ['cat', 'dog']

# Groups
text = "abcabc abc"
print(re.findall(r'(abc)+', text))       # ['abc'] (captures last group)
print(re.findall(r'(?:abc)+', text))     # ['abcabc', 'abc'] (non-capturing)

# Escape Sequences
text = "Price: $10.99 + tax"
print(re.findall(r'\$\d+\.\d+', text))   # ['$10.99']

Common Pattern Combinations

python

# Email pattern
email_pattern = r'[\w\.-]+@[\w\.-]+\.\w+'

# Phone number pattern (basic)
phone_pattern = r'\d{3}[-.]\d{3}[-.]\d{4}'

# URL pattern (basic)
url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'

# Date pattern (MM/DD/YYYY)
date_pattern = r'\d{2}/\d{2}/\d{4}'

Remember to use raw strings (r'pattern') for regular expressions to avoid issues with backslash escaping!

Similar Posts

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  • What is list

    In Python, a list is a built-in data structure that represents an ordered, mutable (changeable), and heterogeneous (can contain different data types) collection of elements. Lists are one of the most commonly used data structures in Python due to their flexibility and dynamic nature. Definition of a List in Python: Example: python my_list = [1, “hello”, 3.14,…

  • Finally Block in Exception Handling in Python

    Finally Block in Exception Handling in Python The finally block in Python exception handling executes regardless of whether an exception occurred or not. It’s always executed, making it perfect for cleanup operations like closing files, database connections, or releasing resources. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else:…

  • What are Variables

    A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasks—whether it’s calculating numbers, playing a song, displaying a website, or running a game. Programs are written in programming languages like Python, Java, or C++,…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

Leave a Reply

Your email address will not be published. Required fields are marked *