re.fullmatch() Method

Python re.fullmatch() Method Explained

The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t.

Syntax

python

re.fullmatch(pattern, string, flags=0)
import re

# Target string
string = "The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by 11.48% – the worst day since it launched in 1998. The panic selling prompted by the coronavirus has wiped £2.7tn off the value of STOXX 600 shares since its all-time peak on 19 February."

# Source: https://www.theguardian.com/

# Check if the entire string has exactly 285 characters
result = re.fullmatch(r".{285}", string)

print(f"String length: {len(string)} characters")
print(f"re.fullmatch result: {result}")

if result:
    print("✓ The string has exactly 285 characters")
else:
    print("✗ The string does NOT have exactly 285 characters")

# Display the actual matched portion (if any)
if result:
    print(f"\nMatched text: '{result.group()}'")

Output:

text

String length: 285 characters
re.fullmatch result: <re.Match object; span=(0, 285), match='The Euro STOXX 600 index, which tracks all stock >

✓ The string has exactly 285 characters

Matched text: 'The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by 11.48% – the worst day since it launched in 1998. The panic selling prompted by the coronavirus has wiped £2.7tn off the value of STOXX 600 shares since its all-time peak on 19 February.'

In the code re.fullmatch(r".{285}", string), the dot (.) is a special regex character that matches any character except a newline (unless the re.DOTALL flag is used).

What r".{285}" means:

  • . – Matches any single character (except newline by default)
  • {285} – Specifies exactly 285 occurrences of the preceding element
  • So .{285} means “exactly 285 of any characters”

Python re.fullmatch() Method Explained

The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t.

Syntax

python

re.fullmatch(pattern, string, flags=0)

Example 1: Validating Email Format

python

import re

# Validate email format
emails = ["user@example.com", "invalid-email", "name@domain.co.uk", "short@a.b"]

for email in emails:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
match = re.fullmatch(pattern, email)

if match:
print(f"✓ Valid email: {email}")
else:
print(f"✗ Invalid email: {email}")
Let me break down this email validation regex pattern piece by piece:

Pattern: r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
1. ^ - Start of string anchor
Ensures the pattern matches from the very beginning

2. [a-zA-Z0-9._%+-]+ - Local part (before @)
[a-zA-Z0-9._%+-] - Character class matching:

Letters: a-z, A-Z

Digits: 0-9

Special characters: ., _, %, +, -

+ - One or more of these characters

3. @ - Literal @ symbol
Must contain exactly one @ symbol

4. [a-zA-Z0-9.-]+ - Domain name (after @)
[a-zA-Z0-9.-] - Character class matching:

Letters: a-z, A-Z

Digits: 0-9

Special characters: ., -

+ - One or more of these characters

5. \. - Literal dot (escaped)
The dot before TLD (must be escaped with \ because . is a regex metacharacter)

6. [a-zA-Z]{2,} - Top Level Domain (TLD)
[a-zA-Z] - Only letters allowed in TLD

{2,} - Two or more characters (e.g., .com, .org, .io)

7. $ - End of string anchor
Ensures the pattern matches to the very end

What this pattern validates:
text
username@domain.tld
Examples that match:
user@example.com

first.last@company.co.uk

name123@sub.domain.org

user_name+filter@domain.io

Examples that DON'T match:
user@com (TLD too short)

user@.com (domain part empty)

@domain.com (local part missing)

user@domain. (TLD missing)

user@domain.c (TLD too short)

user@-domain.com (hyphen at start of domain)

Visual Breakdown:
text
^[a-zA-Z0-9._%+-]+ @ [a-zA-Z0-9.-]+ \. [a-zA-Z]{2,} $
 │                  │ │               │ │             │
 │                  │ │               │ │             └── End of string
 │                  │ │               │ └── TLD (2+ letters)
 │                  │ │               └── Literal dot
 │                  │ └── Domain name (hostname)
 │                  └── Literal @ symbol
 └── Local part (username)
This is a commonly used email validation pattern that covers most standard email formats while being relatively strict about the structure.

Output:

text

✓ Valid email: user@example.com
✗ Invalid email: invalid-email
✓ Valid email: name@domain.co.uk
✗ Invalid email: short@a.b

Example 2: Password Validation

python

import re

# Validate password: 8+ chars, at least one uppercase, one lowercase, one digit, one special char
passwords = ["StrongP@ss1", "weak", "NoSpecialChar123", "Valid#Pass99"]

for pwd in passwords:
    pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
    match = re.fullmatch(pattern, pwd)
    
    if match:
        print(f"✓ Strong password: {pwd}")
    else:
        print(f"✗ Weak password: {pwd}")

Output:

text

✓ Strong password: StrongP@ss1
✗ Weak password: weak
✗ Weak password: NoSpecialChar123
✓ Strong password: Valid#Pass99

Example 3: Date Format Validation

python

import re

# Validate dates in YYYY-MM-DD format
dates = [
    "2023-12-25",
    "2023-02-30",  # Invalid date (February 30th)
    "23-12-25",    # Wrong format
    "2023-13-01",  # Invalid month
    "2023-12-25 extra"  # Extra characters
]

for date in dates:
    pattern = r'^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$'
    match = re.fullmatch(pattern, date)
    
    if match:
        print(f"✓ Valid date format: {date}")
    else:
        print(f"✗ Invalid date format: {date}")

Output:

text

✓ Valid date format: 2023-12-25
✓ Valid date format: 2023-02-30  # Note: Pattern validates format, not actual date validity
✗ Invalid date format: 23-12-25
✗ Invalid date format: 2023-13-01
✗ Invalid date format: 2023-12-25 extra

Key Differences from Other Methods

  • re.fullmatch(): Entire string must match pattern
  • re.match(): Pattern must match from the beginning of string
  • re.search(): Pattern can match anywhere in the string

python

import re

text = "abc123def"
pattern = r'\d+'

print("fullmatch:", re.fullmatch(pattern, text))  # None (entire string isn't digits)
print("match:", re.match(pattern, text))         # None (doesn't start with digits)
print("search:", re.search(pattern, text))       # Match object (finds '123')

The re.fullmatch() method is particularly useful for validation tasks where you need to ensure the entire input conforms to a specific pattern.

Similar Posts

  • Class 10 String Comparison ,Bitwise Operators,Chaining Comparisons

    String Comparison with Relational Operators in Python 💬⚖️ In Python, you can compare strings using relational operators (<, <=, >, >=, ==, !=). These comparisons are based on lexicographical (dictionary) order, which uses the Unicode code points of the characters. 📖 How String Comparison Works 🤔 Examples 💡 Python Important Notes 📌 String comparison is…

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • 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,…

  •  List operators,List Traversals

    In Python, lists are ordered, mutable collections that support various operations. Here are the key list operators along with four basic examples: List Operators in Python 4 Basic Examples 1. Concatenation (+) Combines two lists into one. python list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3,…

  • 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}”,…

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

Leave a Reply

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