Python Regular Expressions
Regular expressions (regex) are used to search for patterns in text. Python provides the re module for working with regular expressions.
Basic Regex Syntax
Here are some basic regular expression patterns:
^- Matches the start of the string.$- Matches the end of the string..*- Matches any character (except a newline) zero or more times.\d- Matches any digit.\w- Matches any word character (alphanumeric plus underscore).
Using re Module
You can use the re module to search for patterns in a string. Here's an example of using re.search() to find if a string contains a number:
import re
pattern = r"\d+" # Matches one or more digits
text = "My number is 12345"
result = re.search(pattern, text)
if result:
print("Found a number:", result.group())
else:
print("No number found.")
This code searches for one or more digits in the string and prints the first match found.
Activity
Try It Yourself!
Write a program that uses regular expressions to find all the email addresses in a text.
Quick Quiz
Quick Quiz
- What does the
\dpattern match? - How do you search for a pattern in a string using Python?
Answers: The \d pattern matches any digit. You can search for a pattern using re.search() or re.findall().