Regex is a superpower that most developers fear. Let me demystify it with practical patterns you'll use daily.
Essential Syntax
// Character classes
\\d // digit [0-9]
\\w // word char [a-zA-Z0-9_]
\\s // whitespace
. // any char except newline
[abc] // a, b, or c
[^abc] // NOT a, b, or c
// Quantifiers
* // 0 or more
+ // 1 or more
? // 0 or 1
{3} // exactly 3
{2,5} // 2 to 5
// Anchors
^ // start of string
$ // end of string
\\b // word boundaryPractical Patterns
// Email validation (simplified)
const email = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;
// URL extraction
const urls = /https?:\\/\\/[^\\s]+/g;
// Phone number (flexible)
const phone = /\\+?\\d{1,3}[-.\\s]?\\(?\\d{1,4}\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}/;
// Password strength (min 8 chars, uppercase, lowercase, digit, special)
const strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$/;
// HTML tag stripping
const stripped = html.replace(/<[^>]*>/g, "");Named Groups
const dateRegex = /(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})/;
const match = "2024-01-15".match(dateRegex);
console.log(match.groups.year); // "2024"
console.log(match.groups.month); // "01"Lookahead and Lookbehind
// Positive lookahead: match "foo" followed by "bar"
/foo(?=bar)/ // matches "foo" in "foobar", not in "foobaz"
// Negative lookahead: match "foo" NOT followed by "bar"
/foo(?!bar)/ // matches "foo" in "foobaz", not in "foobar"
// Lookbehind
/(?<=\\$)\\d+/ // match digits preceded by $: "$100" → "100"Performance Tips
- Avoid catastrophic backtracking:
/(a+)+$/is O(2^n) on non-matching strings - Use non-greedy quantifiers (
*?,+?) when possible - Anchor patterns with
^and$ - Cache compiled RegExp objects — don't create new ones in loops
- Use
String.includes()instead of regex for simple substring checks