filmov
tv
Python One-Liner: Validate an Email Address with Regex! ✉️✔️ #PythonTips #CodingShorts

Показать описание
Email validation is a common task for form processing, data cleaning, and user-input verification.
Regex Pattern:
^[\w\.\+\-]+ → One or more word characters, dots, pluses or hyphens before the @.
@[\w\-]+ → An @ followed by one or more word characters or hyphens.
\.[a-zA-Z]{2,}$ → A dot and 2+ letters at the end.
Long Way:
Import the re module.
Loop over example emails, printing each alongside its validity.
One-Liner:
Ideal for quick checks in scripts or interactive sessions.
This one-liner runs in O(n) time where n is the length of the email string and covers most common email formats—perfect for form validation or preprocessing in Jupyter notebooks!
Codes:
# Long Way: Define and use an email-validation function
import re
def is_valid_email(email):
"""
Returns True if the email matches a basic RFC-style regex,
else False.
"""
pattern = r'^[\w\.\+\-]+@[\w\-]+\.[a-zA-Z]{2,}$'
# Example usage:
for e in tests:
print(e, is_valid_email(e))
# Output:
# One-Liner: Inline regex fullmatch
import re
# Output: True
Regex Pattern:
^[\w\.\+\-]+ → One or more word characters, dots, pluses or hyphens before the @.
@[\w\-]+ → An @ followed by one or more word characters or hyphens.
\.[a-zA-Z]{2,}$ → A dot and 2+ letters at the end.
Long Way:
Import the re module.
Loop over example emails, printing each alongside its validity.
One-Liner:
Ideal for quick checks in scripts or interactive sessions.
This one-liner runs in O(n) time where n is the length of the email string and covers most common email formats—perfect for form validation or preprocessing in Jupyter notebooks!
Codes:
# Long Way: Define and use an email-validation function
import re
def is_valid_email(email):
"""
Returns True if the email matches a basic RFC-style regex,
else False.
"""
pattern = r'^[\w\.\+\-]+@[\w\-]+\.[a-zA-Z]{2,}$'
# Example usage:
for e in tests:
print(e, is_valid_email(e))
# Output:
# One-Liner: Inline regex fullmatch
import re
# Output: True