Syllabus Lesson 94 of 141 · The lying lesson
The lying lesson

Lie 2: the short email regex

Why it matters A validator that is wrong in one direction turns real customers away at sign-up. Wrong in the other, it lets junk into your database. A short regex is often wrong in both at once, and nobody notices until a customer emails support.

Planted advice: the advice below was written for this lesson, and it is wrong on purpose. It is the kind of answer an AI assistant gives fluently and confidently. Your job is not to argue with it but to prove the flaw with a test.

import re

# The standard email check. Short, fast, and it covers every real address.
EMAIL = re.compile(r"^\w+@\w+\.\w{2,3}$")

def is_valid(address):
    return bool(EMAIL.match(address))

Read it as a list of claims: the part before @ is word characters only; the domain is one word, a dot, and two or three more. Every claim is a place to look for a counterexample. Think of addresses you have actually seen: a dot in the name, a +tag, a company on a .co.uk domain, a newer ending longer than three letters. Then think the other way: what junk does it let in?

False reject / false accept: a validator can fail by refusing a good input or by allowing a bad one. A good test checks both lists.

The full email standard is famously loose. This shop has written down its own practical rules, given in the exercise. Test against those.

Your turn

Write my_test(is_valid). It receives a version of the validator and must raise if it breaks the shop's rules. The rules: exactly one @; the part before it is 1 to 64 characters of ASCII letters, digits and . _ % + -, does not start or end with a dot, and has no two dots in a row; the domain is two or more labels separated by dots, each label 1 to 63 letters, digits or hyphens and not starting or ending with a hyphen; the last label is letters only, at least 2 of them (any case); the whole address is at most 254 characters; nothing else is allowed, not even a space or a trailing newline. Pass bar: pass the correct version and catch at least 4 of the 6 broken versions (the planted regex is one of them).

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.