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

  • Type Conversion Functions

    Type Conversion Functions in Python 🔄 Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) 🔢 Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) 💬 Converts x…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

Leave a Reply

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