Coding
Parsing & Data

Validate an Email Address

Difficulty

Asked at Valkyrie Trading

Theory: Parsing and Data Hygiene

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

The coding task on a junior derivatives trader online assessment, as two candidates reported it: "the regex for an email address which might contain an underscore". That was the whole instruction. No function name, no signature, no list of what counts as valid, and one of the two never reached it because the earlier questions took the time. This version states the rule, so the work is the pattern and not the guessing.

Implement is_valid_email(s) returning True when s is a valid address and False otherwise. A valid address is:

  • Exactly one @, with a local part before it and a domain after it.
  • The local part is 1 to 64 characters from letters, digits, ., _ and +. It starts and ends with a letter or digit, and never has two dots in a row.
  • The domain is two or more labels separated by single dots. Each label is 1 to 63 characters from letters, digits and -, and does not start or end with -.
  • The last label (the top-level domain) is letters only and at least 2 characters long.
  • No whitespace anywhere, and ASCII only: an accented letter is invalid.

Letter case does not matter: [email protected] is valid.

Examples

is_valid_email("[email protected]")
# True

is_valid_email("jane [email protected]")
# False  (a space)

(is_valid_email("[email protected]"), is_valid_email("trader@example"))
# (True, False)
# an underscore, a plus and four labels are fine; one label is not a domain

Constraints

  • s is a str of length at most 320.
  • The hidden tests are a wall of near-misses: a dot at either end of the local part, two dots in a row, a hyphen at the edge of a label, a missing top-level domain, a trailing newline, a second @, and an accented letter. There is also a run of 200,000 generated addresses, which is worth compiling the pattern once for.
Rate this problem
Language: Python 3.12is_valid_email
Rate this problem