Write a function that checks whether a string looks like a valid email address.
is_valid_email(s)
An address needs: one or more characters (letters, digits, ., +, or -), then @, then one or more characters (letters, digits, or -), then a ., then a final segment. This is a simplified check, not full email-spec validation.
is_valid_email("ada@example.com") // → True
is_valid_email("a.b+c@sub.example.co") // → True
is_valid_email("not-an-email") // → False (no @)
is_valid_email("@example.com") // → False (nothing before @)
is_valid_email("ada@") // → False (nothing after @)
import re
def is_valid_email(s):
return re.fullmatch(r"[\w.+-]+@[\w-]+\.[\w.-]+", s) is not None
Break the pattern into the pieces the description lays out:
[\w.+-]+ — the part before @. A character set containing \w (letters/digits/underscore), plus literal ., +, and -, one or more of them.@ — a literal @ character.[\w-]+ — the domain name (before the final dot): word characters or hyphens, one or more.\. — a literal dot. Note the backslash: an unescaped . in regex means "any character", not specifically a period — you have to escape it (\.) to match a literal dot.[\w.-]+ — the final segment (like com, or sub.example.co if there are multiple dots), which can itself contain more dots.re.fullmatch requires the entire input string to match this whole pattern, front to back — that's what correctly rejects "@example.com" (nothing before @, so [\w.+-]+ — which requires at least one character — can't match anything there) and "ada@" (nothing after @ for the rest of the pattern to match).
This is a deliberately simplified check — real email validation is notoriously more complex (RFC 5322 email addresses allow far stranger forms than most people expect) — but it correctly handles the common shape of a real address.
import re
def is_valid_email(s):
return re.fullmatch(r"[\w.+-]+@[\w-]+\.[\w.-]+", s) is not None
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.