Skip to content

Regular Expressions

Regular Expressions

Regular expressions (regex) are patterns used to match, search, and validate strings. Python provides the built-in re module for working with regex.

Basic Validation Example

import re

pattern = re.compile('this')
string = 'search inside of this text please!'


match = re.search('this', string)       # returns a match object if 'this' is found in the string, otherwise returns None
match1 = pattern.search(string)          # same as above, using compiled pattern

print(match.start())   # starting index
print(match.end())     # ending index
print(match.span())    # (start, end) tuple
print(match.group())   # matched text

a = pattern.findall(string)          # returns a list of all occurrences of 'this' in the string
b = pattern.fullmatch(string)       # checks if the entire string matches the pattern, returns a match object if it does, otherwise returns None
c = pattern.match(string)           # checks for a match only at the beginning of the string, returns a match object if it does, otherwise returns None

Groups in Regex

You can capture groups using parentheses ().

pattern1 = re.compile(r"([a-zA-Z]).([a])")
string1 = 'search inside of this text please!'
match1 = pattern1.search(string1)
print(match1.group())        # returns a tuple of all the groups in the pattern that match the string

Email Validation

email_pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')

email = "whatever@gmail.com"

a = email_pattern.search(email)
print(a)

if email_pattern.match(email):
    print("Valid email address")
else:
    print("Invalid email address")

Password Validation

Example: at least 8 characters, letters, numbers, and special symbols $%#@.

password_pattern = re.compile(r'^[a-zA-Z0-9$%#@]{8,}\d$')
password = "password123$1"

check = password_pattern.fullmatch(password)
print(check)

🔗 Useful Regex Resources