Introduction
In today’s digital world, email addresses are an essential part of communication. However, ensuring that an email address is properly formatted is equally important for preventing errors or ensuring smooth functionality of email-based services. This program aims to validate whether a given string is a correctly formatted email address by checking various patterns such as the presence of the “@” symbol, a domain name, and valid characters.
Objective
The goal of this Python program is to implement a function that checks if an input string follows the proper syntax of an email address. It will use regular expressions to match the structure of a valid email address, which includes the username, ‘@’ symbol, and domain with a valid extension.
Python Code
import re # Function to validate an email address using regex def is_valid_email(email): # Regular expression pattern for validating an email email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' # Using re.match to check if the email matches the pattern if re.match(email_pattern, email): return True else: return False # Main code to take user input and validate the email if __name__ == "__main__": email = input("Enter the email address to validate: ") if is_valid_email(email): print(f"The email address '{email}' is valid.") else: print(f"The email address '{email}' is not valid.")
Explanation of the Program
The program uses Python’s built-in re
module, which provides support for working with regular expressions. The function is_valid_email
takes an email string as input and applies a regular expression pattern that matches typical email formats.
Here’s a breakdown of the email validation regular expression:
- ^[a-zA-Z0-9_.+-]+: The email’s local part (before the @ symbol) must contain one or more alphanumeric characters or special characters such as
._+-
. - @: The “@” symbol separates the local part from the domain part.
- [a-zA-Z0-9-]+: The domain name (after the @ symbol) can contain alphanumeric characters or hyphens.
- \.[a-zA-Z0-9-.]+$: The domain extension must begin with a dot followed by alphanumeric characters or hyphens. The extension can have multiple periods (for example, .co.uk).
The program takes the user’s email input, validates it using the regular expression, and outputs whether the email address is valid or not.
How to Run the Program
Follow these steps to run the program:
- Install Python (if not already installed) from Python Official Website.
- Save the Python code to a file (e.g.,
email_validation.py
). - Open a terminal or command prompt.
- Navigate to the directory where the file is saved.
- Run the program by typing the command:
python email_validation.py
. - Enter an email address when prompted to check its validity.