Practical Examples and Use Cases
One common use case for the match()
function is to validate user input. For example, you can use it to check if a user's email address or phone number matches a specific pattern.
import re
## Validate email address
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
email = "[email protected]"
if re.match(email_pattern, email):
print("Valid email address")
else:
print("Invalid email address")
## Validate phone number
phone_pattern = r'^\+?\d{1,3}?[-\s]?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$'
phone = "+1 (123) 456-7890"
if re.match(phone_pattern, phone):
print("Valid phone number")
else:
print("Invalid phone number")
Another use case for the match()
function is to extract information from filenames. For example, you can use it to identify the file type or extract the date from a filename.
import re
## Extract file type from filename
filename = "document_2023-04-15.pdf"
file_pattern = r'\.(\w+)$'
match_obj = re.match(file_pattern, filename)
if match_obj:
file_type = match_obj.group(1)
print(f"File type: {file_type}")
else:
print("Unable to determine file type")
## Extract date from filename
date_pattern = r'(\d{4}-\d{2}-\d{2})'
match_obj = re.match(date_pattern, filename)
if match_obj:
file_date = match_obj.group(1)
print(f"File date: {file_date}")
else:
print("Unable to determine file date")
Splitting Strings Based on Patterns
The match()
function can also be used in combination with other string manipulation functions, such as split()
, to split strings based on specific patterns.
import re
## Split a string on comma-separated values
csv_data = "apple,banana,cherry,date"
csv_pattern = r',+'
parts = re.split(csv_pattern, csv_data)
print("CSV parts:", parts)
## Split a sentence into words
sentence = "The quick brown fox jumps over the lazy dog."
word_pattern = r'\w+'
words = re.findall(word_pattern, sentence)
print("Words:", words)
By exploring these practical examples and use cases, you can gain a better understanding of how to effectively leverage the match()
function in your Python programming tasks.