Welcome to our comprehensive guide on Python Regex Patterns! In this lesson, we'll explore Regular Expressions (Regex) - a powerful tool for matching and manipulating text. We'll start from the basics and work our way up to advanced examples, making this lesson suitable for beginners as well as intermediate learners.
Regex is a sequence of characters that forms a search pattern. It's used to search, manipulate, or match strings of text according to the pattern specified. Python's re module provides support for regular expressions.
. : Matches any single character except a newline.\d : Matches any digit (0-9).\w : Matches any word character (alphanumeric and underscore).\s : Matches any whitespace character.^ : Matches the start of a line.$ : Matches the end of a line.* : Zero or more occurrences of the preceding character or pattern.+ : One or more occurrences of the preceding character or pattern.? : Zero or one occurrence of the preceding character or pattern.{} : Matches a specific number of occurrences of the preceding character or pattern.import re
def find_emails(text):
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
emails = re.findall(email_pattern, text)
return emails
text = "My email is example@example.com and my friend's email is friend@example.net"
emails = find_emails(text)
print(emails)In this example, we're using the findall function from Python's re module to find all email addresses in a given text.
We'll explore more complex patterns and techniques, including grouping, lookarounds, and backreferences.
What does the special character `\d` match in a regular expression?
Stay tuned for the next part of our Python Regex Patterns lesson, where we'll dive deeper into advanced concepts and provide more practical examples! 🚀