Top 10 Regex Patterns Every Developer Should Know

Regular expressions (regex) are a compact and powerful language for pattern-matching and text processing. Learning a few reliable patterns can dramatically speed up tasks like validation, parsing logs, and extracting data. Below are ten patterns that are useful across many projects — with brief explanations and examples.

1. Match only digits

^\d+$ — matches strings that are entirely digits (e.g., "12345"). Use for numeric IDs or codes.

2. Match only letters

^[A-Za-z]+$ — matches alphabetic strings. Useful when restricting input to letters only.

3. Basic email validation

^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ — a practical email validator for many use cases. Note: email validation can be complicated for every RFC nuance; use this for simple checks.

4. URL detection

https?:\/\/[^\s]+ — finds http or https URLs in text. Pair with stricter parsing for production use.

5. Word boundary match

\bword\b — ensures you match a whole word, not substrings. Helpful in search and natural language tasks.

6. Capture groups for extraction

(\d{4})-(\d{2})-(\d{2}) — extracts year, month, day from ISO-like date strings. Use capture groups to pull parts into variables.

7. Optional groups

^(\+?\d{1,3})?[-.\s]?\d{10}$ — a phone number pattern allowing an optional country code. Optional groups are powerful for flexible input formats.

8. Non-greedy matching

<.*?> — using ? after * makes the quantifier non-greedy, matching the shortest possible string. Useful when parsing HTML-like snippets.

9. Alternation (or)

cat|dog|rabbit — matches either "cat", "dog" or "rabbit". Alternation is simple but effective for enumerating known tokens.

10. Validate hex colors

^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$ — matches 3- or 6-digit hex color codes with optional leading "#". Handy in styling and design tools.

Tips for using regex safely

  • Avoid catastrophic backtracking by limiting nested quantifiers and preferring atomic or possessive quantifiers when available.
  • Always test your patterns with representative input sets — edge cases often surface unexpected behavior.
  • Use named capture groups where supported to improve readability, e.g. (?<year>\d{4}).

If you want, try these patterns in our AI Regex Generator to see live examples and explanations.