Regular Expression Fundamentals
Common Regex Patterns & Syntax
Regular expressions are patterns used to match character combinations in strings. Here are essential syntax elements:
Character Classes
\d– Any digit (0-9)\w– Word character (a-z, A-Z, 0-9, _)\s– Whitespace (space, tab, newline).– Any character except newline[abc]– Any of a, b, or c[^abc]– Not a, b, or c[a-z]– Character range
Quantifiers
*– 0 or more+– 1 or more?– 0 or 1{3}– Exactly 3{3,}– 3 or more{3,5}– Between 3 and 5
Anchors & Boundaries
^– Start of string/line$– End of string/line\b– Word boundary\B– Not word boundary
Groups & Lookarounds
(abc)– Capture group(?:abc)– Non-capturing group(?=abc)– Positive lookahead(?!abc)– Negative lookahead(?<=abc)– Positive lookbehind(?<!abc)– Negative lookbehind
Common Use Cases
Email Validation: ^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$
URL Matching: https?://(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)
Phone Numbers: ^(\+\d{1,3}[-.]?)?\(?\d{3}\)?[-.]?\d{3}[-.]?\d{4}$
Date (YYYY-MM-DD): ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Frequently Asked Questions
Regex flags (also called modifiers) change how the pattern matching works:
- g (global): Find all matches, not just the first one
- i (case-insensitive): Case insensitive matching (A matches a)
- m (multiline): ^ and $ match start/end of each line, not just whole string
- s (dotAll): Dot (.) matches newline characters as well
- u (unicode): Enable full Unicode matching
- y (sticky): Match only from the index indicated by lastIndex property
Example: /test/gi will find all occurrences of “test”, “Test”, “TEST”, etc.
Flags can be combined: /pattern/gim applies global, case-insensitive, and multiline modes together.
Common reasons for regex matching issues:
Matching Too Much (Greedy Quantifiers)
By default, quantifiers (*, +, {n,}) are greedy – they match as much as possible.
Solution: Use lazy quantifiers by adding ?:
.*→.*?(matches minimum characters).+→.+?.{3,5}→.{3,5}?
Matching Too Little (Word Boundaries)
Missing word boundaries (\b) can cause partial word matches.
Example: /cat/ matches “cat” in “concatenate”
Solution: /\bcat\b/ only matches whole word “cat”
Anchoring Issues
Without ^ (start) and $ (end), patterns match anywhere in the string.
Example: /^\d{3}$/ matches exactly “123” but not “1234” or “a123”
Complex validations often require balanced approaches:
Email Validation
Simple (covers most cases): ^\S+@\S+\.\S+$
More comprehensive: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Note: Perfect email validation with regex alone is nearly impossible due to complex RFC specifications.
URL Validation
Basic URL: ^https?://\S+$
With domain validation: ^https?://(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(/\S*)?$
Best Practices
- Start simple and add complexity as needed
- Consider using multiple regex patterns for different cases
- Test with both valid and invalid examples
- For production, use established validation libraries when possible
- Remember: Regex validates format, not existence
Lookarounds are zero-width assertions that check for patterns without including them in the match.
Lookaheads (check ahead)
- Positive lookahead
(?=...): Match if followed by pattern - Negative lookahead
(?!...): Match if NOT followed by pattern
Example: /\d(?=px)/ matches digits only if followed by “px” (matches “10” in “10px” but not in “10em”)
Lookbehinds (check behind)
- Positive lookbehind
(?<=...): Match if preceded by pattern - Negative lookbehind
(?<!...): Match if NOT preceded by pattern
Example: (?<=\$)\d+ matches digits only if preceded by “$” (matches “100” in “$100” but not in “€100”)
Common Use Cases
- Password validation:
(?=.*[A-Z])(?=.*\d).{8,}(requires uppercase AND digit) - Extracting content:
(?<=Chapter \d: ).*(text after “Chapter X: “) - Excluding patterns:
\b(?!exclude)\w+\b(words except “exclude”)
Browser Support: Lookbehinds ((?<=...)) may not work in older browsers.