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

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

Leave a Reply

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