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
re.compilebuilds a reusable pattern.fullmatchrequires the entire string to match.- Wrapping it in a helper gives a clean boolean check.
Keywords and builtins used here
defreturnvalid_colorvalid_email
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.
Step 4 of 5 in Regular expressions, step 4 of 41 in Domain tools.