Regular Expressions (Regex) Guide
Regular expressions (Regex) help you search, match, and replace text patterns. They work across all major programming languages like JavaScript, Python, Go, and PHP. You can use regex to validate form inputs, parse server logs, and clean data quickly.
1. How Regex Works
Regex engines scan your text character by character to find matches. - **NFA Engines:** Used by JavaScript, Python, and Java. They support backreferences and lookaheads. - **DFA Engines:** Used by Go and Rust regex. They run fast and guarantee predictable execution times.
2. Common Characters & Anchors
Here are the basic building blocks of regex: - `\d`: Matches any single digit from 0 to 9. - `\w`: Matches any word character (letters, numbers, underscores). - `\s`: Matches whitespace (spaces, tabs, newlines). - `^`: Matches the start of a string or line. - `
3. Lookaheads & Lookbehinds
Lookarounds check surrounding text without including it in the final match: - **Positive Lookahead `(?=...)`:** Checks if a pattern comes next (example: `(?=.*\d)` requires at least one digit). - **Negative Lookahead `(?!...)`:** Checks that a pattern does NOT come next. - **Positive Lookbehind `(?<=...)`:** Checks if a pattern comes before the match. - **Negative Lookbehind `(?<!...)`:** Checks that a pattern does NOT come before the match.
4. Keeping Regex Fast & Safe
Bad regex patterns can freeze your server if they take too long to run. This is called **ReDoS** (Regular Expression Denial of Service). Follow these simple rules: - Avoid nesting repetition like `(a+)+`. - Use specific character sets instead of broad wildcards like `.*`. - Test patterns on edge cases before deploying to production.
Engineering Best Practices & Guidelines
Always start with `^` and end with `
Use `[0-9]` or `\d` instead of `.` to avoid matching unexpected characters.
Use non-capturing groups `(?:...)` if you do not need to save the match.
Test your patterns with sample inputs using our free online Regex Tester.
Frequently Asked Questions
Q1. What is greedy vs lazy matching?
Greedy matching ( or +) matches as much text as possible. Lazy matching (? or +?) matches as little text as needed.
Q2. What does the 'g' flag mean in regex?
The 'g' flag stands for global search. It finds all matches in the text instead of stopping after the first one.
Q3. How do I test regex safely?
Use client-side tools like our online Regex Tester to test expressions in your browser before using them in server code.