Python Examples: regular expressions
import re
def is_valid_email(email):
"""Returns True if the given email address is valid, False otherwise"""
pattern = r'^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+.[a-zA-Z]{2,})$'
return bool(re.match(pattern, email))
# Example usage:
print("is example@email.com valid - ", is_valid_email("example@email.com")) # True
print("is invalid.email@com valid - ", is_valid_email("invalid.email@com")) # False
# example using match groups
def extract_email_domain(email):
pattern = r'^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+.[a-zA-Z]{2,})$'
match = re.match(pattern, email)
if match:
return match.group(1)
return None
print("email domain for example@email.com is - ", extract_email_domain("example@email.com")) # True
print("email domain for invalid.email@com is - ", extract_email_domain("invalid.email@com")) # False
# example using named match groups
def parse_date(date_string):
"""Parses a date string in the format 'DD/MM/YYYY' and returns a dictionary with the day, month, and year"""
pattern = r'(?P<day>d{2})/(?P<month>d{2})/(?P<year>d{4})'
match = re.match(pattern, date_string)
if match:
return match.groupdict()
else:
return None
date_string = '18/03/2023'
date_dict = parse_date(date_string)
print(date_dict)