typestar

Regex validation in Python

Using fullmatch to check that a whole string fits.

import re

EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")


def valid_email(text):
    return EMAIL.fullmatch(text) is not None


def valid_color(text):
    return HEX_COLOR.fullmatch(text) is not None


ok = valid_email("ada@lovelace.dev")
bad = valid_email("not an email")
teal = valid_color("#2aa198")

How it works

  1. re.compile builds a reusable pattern.
  2. fullmatch requires the entire string to match.
  3. Wrapping it in a helper gives a clean boolean check.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
339
Tokens
89
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 4 of 5 in Regular expressions, step 4 of 41 in Domain tools.

← Previous Next →