Coding Techniques
Regular Expressions · Study material
Compile once, reuse everywhere
A compiled pattern with anchors validates input reliably. Here: an optional +91 prefix, then a 10-digit Indian mobile number starting with 6–9.
import re
PHONE = re.compile(r"^(?:\+91[-\s]?)?[6-9]\d{9}$") # compile once, reuse many times
numbers = ["9845012345", "+91 9845012345", "+91-7012345678", "5845012345", "98450"]
for n in numbers:
print(f"{n:<16} {'valid' if PHONE.match(n) else 'invalid'}")
9845012345 valid +91 9845012345 valid +91-7012345678 valid 5845012345 invalid 98450 invalid
Handy patterns
| Goal | Pattern |
|---|---|
| Whole number | ^-?\d+$ |
| Decimal number | ^-?\d+(\.\d+)?$ |
| Indian PIN code | ^[1-9]\d{5}$ |
| Simple email | ^[\w.+-]+@[\w-]+\.[\w.]+$ |
| Date DD-MM-YYYY | ^\d{2}-\d{2}-\d{4}$ |
| Hashtags | #\w+ |
| Repeated words | \b(\w+) \1\b |
| Extra spaces | \s+ → " " |
Safe matching pattern
import re
m = re.search(r"Order #(\d+)", text)
if m: # a failed search returns None
order_id = int(m.group(1))
else:
order_id = None
order_id = int(m.group(1)) if (m := re.search(r"Order #(\d+)", text)) else None # same with := Regex checklist
- Use raw strings r"…".
- Use fullmatch (or ^…$) for validation.
- Check for None before calling .group().
- Escape literal dots and brackets; use re.escape for user text.
- Prefer lazy quantifiers or negated classes over greedy .*.
- Use named groups for readable extraction.
- Use re.VERBOSE to comment long patterns.