Regex basics
A regex pattern is just a compact way to describe text you want to match. Start simple: match one thing, test it, then add groups, anchors, or quantifiers only when needed.
Anchors
^ means start of input and $ means end of input.
Character classes
[0-9], [A-Z], and [a-z] match ranges.
Quantifiers
* = zero or more, + = one or more, ? = optional.
Common patterns
| Use case | Pattern | Notes |
|---|---|---|
| ^[^\s@]+@[^\s@]+\.[^\s@]+$ | Good general-purpose validation, not a full RFC parser. | |
| URL | https?:\/\/[^\s]+ | Matches basic HTTP and HTTPS links. |
| Whole number | ^-?\d+$ | Supports optional negative sign. |
| Decimal number | ^-?\d+(\.\d+)?$ | Matches integers and decimals. |
| Whitespace | \s+ | Useful for collapsing repeated spaces and line breaks. |
| Hex color | ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ | Supports 3-digit and 6-digit colors. |
| IPv4 | \b(?:\d{1,3}\.){3}\d{1,3}\b | Matches IPv4-like text, not strict 0-255 validation. |
| Blank lines | ^\s*$ | Use with multiline mode to target empty rows. |
Flags you use most often
g global
Find all matches instead of stopping after the first match.
i ignore case
Makes matching case-insensitive, useful for keywords and user input.
m multiline
Makes ^ and $ work line by line.
s dotall
Lets . match line breaks as well as normal characters.
Common regex pitfalls
- Do not start with a giant all-in-one pattern. Build incrementally and test each part.
- Remember to escape special characters like ., ?, +, and [ when you mean the literal character.
- If you only want whole words, add boundaries like \bword\b.
- Be careful with greedy matching. .* often captures more than you expect.
Use this reference with the right tool
Look up a pattern here, then test it live, apply it to real text, or use it in a replacement workflow.