Quick Reference
. Any character\d Digit [0-9]\w Word char [a-zA-Z0-9_]\s Whitespace^ Start of string$ End of string* Zero or more+ One or more? Zero or one{n} Exactly n times[abc] Character set(...) Capture groupRegex Flags Explained
g (global) — Find all matches in the string, not just the first one. Without this flag, only the first match is returned.
i (ignore case) — Make the pattern case-insensitive. "A" matches "a" and vice versa.
m (multiline) — Treat ^ and $ as line boundaries instead of string boundaries. Useful for multi-line text.
s (dotall) — Allow . to match newline characters. Without this flag, . matches everything except newlines.
Global vs Single Match
Without the g flag, the regex returns only the first match with detailed capture group information. This is useful when you need to extract specific parts of a single match.
With the g flag, the regex finds all matches in the string. Each match shows its position (start and end index) so you can locate it in your original text.
For patterns with capture groups, use g flag with
matchAll() behavior to see groups for each match.
Capture Groups and What They Return
Capture groups are created with parentheses () in your pattern. They let you
extract specific parts of a match.
Example: Pattern (\d{4})-(\d{2})-(\d{2}) matching
"2024-03-15" returns:
- Group 0 (full match): "2024-03-15"
- Group 1: "2024" (year)
- Group 2: "03" (month)
- Group 3: "15" (day)
Groups that don't match anything return undefined. Optional groups with
? may be empty.
Common Regex Mistakes
- Forgetting to escape special characters — Characters like . * + ? ^ $ { } [ ] \ | ( ) need escaping with \ when used literally
- Greedy vs lazy quantifiers — Use *? or +? for lazy matching to avoid matching too much
- Wrong character class syntax — Inside [ ], most special characters don't need escaping except ] and \
- Missing anchors — Use ^ and $ to match the entire string, not just a part
- Not using raw strings — In some languages, you need double escaping: \\d instead of \d
How to Test a Pattern Step by Step
- Start simple — Test with a basic pattern first, then add complexity
- Use flags appropriately — Add 'i' for case-insensitive, 'g' for multiple matches
- Check each capture group — Verify groups capture what you expect
- Test edge cases — Try empty strings, special characters, and boundary conditions
- Verify positions — Check start/end indices to ensure matches are where you expect