
import re
Basic patterns:
. — any character
\d — digit, \w — word char, \s — whitespace
^ — start, $ — end
* — 0 or more, + — 1 or more, ? — 0 or 1
{3} — exactly 3, {2,5} — 2 to 5
Key functions:
text = "My phone is 555-867-5309"
re.search(r"\d{3}-\d{3}-\d{4}", text) # first match
re.findall(r"\d+", text) # all numbers: ['555','867','5309']
re.sub(r"\d", "X", text) # replace digits with X
re.match(r"My", text) # only at startGroups:
match = re.search(r"(\d{3})-(\d{3})-(\d{4})", text)
if match:
area = match.group(1) # "555"
full = match.group(0) # entire matchEmail validation example:
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
print("Valid email")Reference:
TaskLoco™ — The Sticky Note GOAT