Your files are processed locally in your browser — never uploaded to any server.
    Developer Tools

    How to Write and Test Regular Expressions Step by Step

    Dec 28, 20246 min read
    Ad

    Regular expressions (regex) are powerful patterns for matching, searching, and manipulating text. They're used in every programming language, text editor, and many command-line tools. While regex can look intimidating, learning the basics opens up incredible text-processing capabilities.

    What Is a Regular Expression?

    A regex is a sequence of characters that defines a search pattern. Instead of searching for an exact string like "hello", you can search for patterns like "any word starting with h" or "any email address" or "any phone number in a specific format".

    Essential Regex Syntax

    Character Classes

    • . — Matches any single character (except newline)
    • \d — Matches any digit (0–9)
    • \w — Matches any word character (letters, digits, underscore)
    • \s — Matches any whitespace (space, tab, newline)
    • [abc] — Matches any one of a, b, or c
    • [^abc] — Matches anything except a, b, or c
    • [a-z] — Matches any lowercase letter

    Quantifiers

    • * — Zero or more times
    • + — One or more times
    • ? — Zero or one time (optional)
    • {3} — Exactly 3 times
    • {2,5} — Between 2 and 5 times

    Anchors

    • ^ — Start of string
    • $ — End of string
    • \b — Word boundary

    Real-World Regex Examples

    Email Validation

    ^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$

    Matches patterns like [email protected], [email protected]

    Phone Number (US format)

    ^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$

    Matches: (555) 123-4567, 555-123-4567, 5551234567

    URL

    https?:\/\/[\w.-]+\.[a-zA-Z]{2,}(\/\S*)?

    Matches http and https URLs

    Step-by-Step: Test a Regex

    1. Open the tool — Go to our Regex Tester.
    2. Enter your pattern — Type your regex in the pattern field.
    3. Add test text — Paste or type the text you want to test against.
    4. See matches — Matches are highlighted in real-time as you type.
    5. Refine — Adjust your pattern and see results update instantly.

    Common Mistakes

    • Not escaping special characters — Characters like . * + ? ( ) [ ] { } \ ^ $ | have special meaning. To match them literally, prefix with \.
    • Greedy vs. lazy matching — By default, * and + are greedy (match as much as possible). Add ? to make them lazy: .*? matches as little as possible.
    • Forgetting anchors — Without ^ and $, your pattern might match anywhere in the string, not just the whole string.

    Practice and test your regex with our Regex Tester — instant feedback, right in your browser.

    Ready to try it?

    Open Regex Tester
    Ad

    Share this page