Valid Email Address Filter – Detailed Version

Опубликовано: 01 Март 2026
на канале: CodeVisium
1,582
8

In this problem, you are given several pairs of names and email addresses in the format:

name v [email protected] v
Your task is to validate each email address and print the pair only if the email address is valid according to the following rules:

Format: The email address must be in the format:

[email protected]

Username Requirements:

Must start with an English alphabet letter (A-Z or a-z).

The subsequent characters can be alphanumeric or one of these special characters: -, ., or _.

Domain and Extension Requirements:

The domain and extension should contain only English alphabetical characters.

The extension must be 1 to 3 characters in length.

No Repeating Characters:

No character should appear more than once in the UID.

Overall Length:

The UID must be exactly 10 characters long (note: this rule applies to another problem; here the UID length rule is not required for email validation).

We use Python’s re module for regular expression matching and the email.utils module to parse the input strings. The program follows these steps:

Input Handling:
The first line of input gives the number of test cases. Each subsequent line contains a name and an email address in the format Name v email v.

Parsing and Validation:
We use email.utils.parseaddr() to separate the name and email address. Then, using a regex pattern, we validate that the email meets the criteria:

It starts with a letter.

The username contains allowed characters.

The domain and extension are purely alphabetical with an extension length of 1 to 3.

Output:

If the email is valid, we print the pair in the original format using email.utils.formataddr(). Otherwise, we ignore it.

This detailed solution is ideal for understanding how to combine regex with Python’s built-in email utilities to solve real-world data validation problems.

Code (Detailed Version):

import re
import email.utils

def is_valid_email(email_addr):
Regex pattern to match a valid email address:
- Username: starts with a letter, followed by one or more alphanumeric characters or - . _
- Domain: only alphabetical characters
- Extension: only alphabetical characters, length 1 to 3
pattern = r'^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z]+\.[A-Za-z]{1,3}$'
return re.match(pattern, email_addr)

def solve():
n = int(input().strip())
for _ in range(n):
s = input().strip()
name, email_addr = email.utils.parseaddr(s)
if is_valid_email(email_addr):
Print in the original format
print(email.utils.formataddr((name, email_addr)))

if _name_ == '__main__':
solve()