Regex Generator

Generate common regular expressions for email, URL, phone, date, and more validation patterns.

Common Patterns

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Matches standard email addresses

user@example.comjohn.doe@company.org

Custom Pattern Builder

^[a-zA-Z]*$

Regex Cheat Sheet

.Any character
\\dDigit (0-9)
\\wWord character (a-zA-Z0-9_)
\\sWhitespace
^Start of string
$End of string
*0 or more
+1 or more
?0 or 1
{n,m}Between n and m
[abc]Character class
(group)Capture group

Tip: Test your regex patterns in the Regex Tester tool before using them in production code.

What Is a Regular Expression?

A regular expression (regex or regexp) is a sequence of characters that defines a search pattern. Developers use regex patterns to validate input, search text, extract data, and perform find-and-replace operations across virtually every programming language and platform. Whether you need to confirm that a user has entered a valid email address, a properly formatted phone number, or a strong password, a well-crafted regex pattern is the most concise and reliable tool for the job.

Regex originated in formal language theory and was popularized by Unix text-processing utilities like grep, sed, and awk in the 1970s. Today, every modern language — JavaScript, Python, Java, PHP, Go, Rust — ships with a built-in regex engine. Because the core syntax is largely standardized (with minor dialect variations), a pattern you learn once transfers across ecosystems.

The regex generator on this page gives you two modes. The Common Patterns selector provides production-ready patterns for the most frequently validated data types: email addresses, URLs, US and international phone numbers, IPv4 and IPv6 addresses, ISO and US date formats, 24-hour time, hex color codes, credit card numbers, Social Security Numbers, ZIP codes, usernames, strong passwords, URL slugs, UUIDs, and HTML tags. Each pattern is displayed alongside its plain-English description and concrete matching examples so you can verify it fits your use case before copying it into your codebase.

The Custom Pattern Builder lets you craft a bespoke regex without memorizing metacharacter syntax. Specify a required prefix, a required suffix, a required substring, minimum and maximum lengths, and the allowed character set. The tool assembles the pattern in real time, escaping any special characters in your literal text so the output is always safe to use directly.

Custom Pattern Builder Formula

Pattern = ^ + escape(startsWith) + [charClass]{min,max} + escape(endsWith) + $

Where:

  • ^= Anchors the match to the start of the string
  • escape(startsWith)= Literal prefix text with all regex metacharacters escaped (e.g. . → \.)
  • [charClass]= Character class derived from the Allowed Characters setting: a-zA-Z (letters), 0-9 (numbers), a-zA-Z0-9 (alphanumeric), or . (any character)
  • {min,max}= Length quantifier built from Min Length and Max Length fields; omitted values default to 0 and unlimited respectively. Replaced by .* when a "Must Contain" substring is provided.
  • escape(endsWith)= Literal suffix text with all regex metacharacters escaped
  • $= Anchors the match to the end of the string

Common Regex Patterns Reference

The table below summarises the eighteen built-in patterns available in the Common Patterns selector. Each entry shows the pattern name, the raw regex, and the data it validates. Use this as a quick reference when you need to remember which pattern to reach for.

Name Pattern Matches
Email^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$Standard email addresses
URL^(https?://)?([\da-z.-]+).([a-z.]{2,6})([\/w .-]*)*/?$URLs with optional protocol
US Phone^(+1)?[-.\s]?(?\d{3})?[-.\s]?\d{3}[-.\s]?\d{4}$US numbers in various formats
Intl Phone (E.164)^+?[1-9]\d{1,14}$International E.164 numbers
IPv4^(25[0-5]|2[0-4]\d|[01]?\d\d?)(.(25[0-5]|2[0-4]\d|[01]?\d\d?)){3}$Valid IPv4 addresses
IPv6^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$Full IPv6 addresses
Date ISO 8601^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$YYYY-MM-DD format
Date US^(0[1-9]|1[0-2])/(0[1-9]|[12]\d|3[01])/\d{4}$MM/DD/YYYY format
Time 24h^([01]\d|2[0-3]):([0-5]\d)$HH:MM 24-hour time
Hex Color^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$3- or 6-digit hex colors
Credit Card^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$Visa, Mastercard, Amex
SSN (US)^(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}$US Social Security Numbers
ZIP Code (US)^\d{5}(-\d{4})?$5-digit and ZIP+4 codes
Username^[a-zA-Z0-9_-]{3,16}$3–16 alphanumeric chars
Strong Password^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$Min 8 chars, mixed case, digit, special
URL Slug^[a-z0-9]+(?:-[a-z0-9]+)*$Lowercase, hyphenated slugs
UUID^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$RFC 4122 UUIDs (v1–v5)
HTML Tag<([a-z]+)([^<]+)*(?:>(.*)</\1>|\s+/>)Opening and self-closing tags

Copy any of these patterns directly from the generator and paste them into your code. They are ready to use as JavaScript RegExp objects, Python re module strings, or PHP preg_match calls with minimal adjustment for delimiter quoting.

How the Custom Pattern Builder Works

The Custom Pattern Builder assembles a regex pattern from plain-English constraints, making it accessible to developers who are not yet fluent in regex metacharacter syntax. Understanding the assembly logic helps you predict the output and troubleshoot edge cases.

Step 1 — Character Class

The Allowed Characters dropdown maps to one of four character classes:

  • Letters onlya-zA-Z — matches any uppercase or lowercase ASCII letter
  • Numbers only0-9 — matches any decimal digit
  • Alphanumerica-zA-Z0-9 — matches letters and digits
  • Any character. — matches any character except a newline (unless the dotall flag is set)

Step 2 — Quantifier

When Min Length and/or Max Length are provided, a bounded quantifier {min,max} is appended to the character class. If only Min Length is set, Max Length defaults to empty (unlimited). If neither is set, the quantifier * (zero or more) is used. For example, Min Length 5 and Max Length 12 with alphanumeric characters produces [a-zA-Z0-9]{5,12}.

Step 3 — Must Contain

When a Must Contain substring is provided, the character-class segment is replaced entirely by .*escape(contains).*. This ensures the literal text appears somewhere in the middle of the string. The Length constraints do not apply when Must Contain is active.

Step 4 — Anchors and Literals

The Starts With value is prepended (after escaping) immediately after the ^ anchor. The Ends With value is appended (after escaping) immediately before the $ anchor. Escaping converts any regex metacharacter in those literals — . * + ? ^ $ { } ( ) | [ ] — into its escaped form so it matches literally. For instance, entering v1.0 as a prefix yields v1.0 in the pattern.

The final pattern always wraps the whole expression in ^ and $ anchors, enforcing a full-string match rather than a substring match. Remove those anchors in your own code if you need to find patterns within a longer string.

Regex Syntax: Metacharacters and Quantifiers

Once you understand the building blocks of regex syntax, you can read, modify, and extend any pattern. The cheat sheet below covers the metacharacters and quantifiers used throughout the patterns on this page.

Anchors

  • ^ — Asserts position at the start of the string (or line in multiline mode)
  • $ — Asserts position at the end of the string (or line in multiline mode)
  •  — Word boundary — the position between a word character and a non-word character

Character Classes

  • \d — Any digit (equivalent to [0-9])
  • w — Any word character (equivalent to [a-zA-Z0-9_])
  • \s — Any whitespace character (space, tab, newline, etc.)
  • [abc] — Matches any of the listed characters
  • [^abc] — Matches any character NOT in the list (negated class)
  • [a-z] — Matches any character in the specified range

Quantifiers

  • * — Zero or more of the preceding element
  • + — One or more of the preceding element
  • ? — Zero or one of the preceding element (makes it optional)
  • {n} — Exactly n repetitions
  • {n,} — At least n repetitions
  • {n,m} — Between n and m repetitions (inclusive)

Groups and Alternation

  • (abc) — Capture group — matches the sequence and captures it for back-references
  • (?:abc) — Non-capturing group — groups without creating a back-reference
  • (?=abc) — Positive lookahead — asserts what follows without consuming characters
  • (?!abc) — Negative lookahead — asserts the following text does NOT match
  • a|b — Alternation — matches either a or b

The strong password pattern uses multiple positive lookaheads ((?=.*[a-z]), (?=.*[A-Z]), (?=.*\d), (?=.*[@$!%*?&])) to require each character category without enforcing a fixed order — a common and elegant pattern worth studying.

Using Generated Regex Patterns in Code

Copying a pattern from the generator is just the first step. Here is how to integrate it correctly in the three most common environments.

JavaScript / Node.js

Use the RegExp constructor or a regex literal. The regex literal form is more concise, but the constructor is required when the pattern is stored as a string:

  • Literal: const emailRe = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
  • Constructor: const emailRe = new RegExp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
  • Test a value: emailRe.test(input) returns true or false

Note that backslashes must be doubled (\d instead of \d) when using the constructor form, because the string itself needs to escape the backslash before the regex engine sees it. The patterns displayed in this generator already use the string-safe double-backslash notation.

Python

Import the re module and use raw strings to avoid double-escaping: pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$'). Then call pattern.match(input) for a full-string match or pattern.search(input)

PHP

PHP's PCRE functions require a delimiter character around the pattern: preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/', $input). If your pattern contains forward slashes (e.g., URL patterns), either escape them as / or use a different delimiter such as # or ~.

Performance Tips

Compile patterns once and reuse the compiled object rather than recreating it on every function call. In JavaScript, move the RegExp object outside your validation function. In Python, store the compiled re.Pattern as a module-level constant. Catastrophic backtracking — where a poorly written pattern causes exponential execution time on adversarial input — is a real denial-of-service risk; avoid nested quantifiers like (a+)+ in patterns that process untrusted user input.

Regex Validation Best Practices

A regex pattern is a powerful first line of defence for input validation, but it works best as part of a layered validation strategy rather than the sole gatekeeper.

Always anchor full-string patterns. Without ^ and $, a pattern like [a-z]{3,16} would match the letters inside a much longer invalid string. The custom builder and all built-in patterns include both anchors automatically.

Validate format, then semantics. A regex can confirm that a date string looks like 2024-02-29, but it cannot confirm that February 29 is valid in the given year without a leap-year calculation. After regex validation passes, run business-logic checks on the parsed value.

Do not use regex as the only security control for SQL, HTML, or shell input. Use parameterised queries for database input, purpose-built HTML sanitisers for rich text, and escaping libraries for shell arguments. Regex cannot reliably block all injection variants and should not be relied upon for security in those contexts.

Handle Unicode explicitly when needed. The character class [a-zA-Z] matches only ASCII letters. For international names and addresses you may need the Unicode property escapes available in JavaScript's ES2018 regex (e.g., \p{L} with the u flag) or PCRE's \pL syntax.

Test with both valid and invalid examples. Confirm that strings you expect to match do match, and that strings you expect to reject are actually rejected. Tools like regex101.com allow interactive testing with detailed match explanations before you commit a pattern to production code.

Worked Examples

Email Address Validation Pattern

Problem:

Validate that a sign-up form field contains a properly structured email address before submitting to the server.

Solution Steps:

  1. 1Select "Email Address" from the Common Patterns dropdown.
  2. 2The generator outputs: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
  3. 3The local part [a-zA-Z0-9._%+-]+ matches one or more letters, digits, dots, underscores, percent signs, plus signs, or hyphens.
  4. 4The literal @ separates the local part from the domain.
  5. 5The domain [a-zA-Z0-9.-]+ matches subdomains and the domain name; \.[a-zA-Z]{2,} requires a dot followed by a TLD of at least two letters.
  6. 6Copy the pattern and use emailRegex.test(input) in JavaScript to validate: "user@example.com" → true, "user@" → false.

Result:

Pattern ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ matches "user@example.com" and "john.doe@company.org" but rejects "user@" and "notanemail".

Custom Alphanumeric Username (5–12 Characters)

Problem:

Build a custom regex for a username field that must be alphanumeric, between 5 and 12 characters long, and contain no spaces or special characters.

Solution Steps:

  1. 1Open the Custom Pattern Builder section of the regex generator.
  2. 2Leave "Starts With" and "Ends With" blank — no required prefix or suffix.
  3. 3Leave "Must Contain" blank — no required substring.
  4. 4Set Min Length to 5 and Max Length to 12.
  5. 5Select "Alphanumeric (a-zA-Z0-9)" from the Allowed Characters dropdown.
  6. 6The builder maps alphanumeric to charClass = a-zA-Z0-9 and constructs the quantifier {5,12}.
  7. 7The tool assembles: ^ + [a-zA-Z0-9]{5,12} + $ = ^[a-zA-Z0-9]{5,12}$

Result:

Pattern ^[a-zA-Z0-9]{5,12}$ matches "alice", "User99", and "Dev123abc" but rejects "ab" (too short), "thisusernameiswaytoolong" (too long), and "user_name" (underscore not allowed).

Custom Pattern for File Names Starting with "img_"

Problem:

Validate image filenames that must start with "img_", end with ".jpg", and contain only alphanumeric characters between prefix and suffix.

Solution Steps:

  1. 1In the Custom Pattern Builder, enter "img_" in the "Starts With" field.
  2. 2Enter ".jpg" in the "Ends With" field. The builder escapes the dot to \.jpg so it matches a literal period, not any character.
  3. 3Leave "Must Contain" blank.
  4. 4Set Min Length to 1 (at least one character between prefix and suffix) and leave Max Length empty.
  5. 5Select "Alphanumeric" for Allowed Characters.
  6. 6The builder escapes "img_" → "img_" (underscore is not a metacharacter, so no change) and ".jpg" → "\.jpg".
  7. 7Pattern assembled: ^img_[a-zA-Z0-9]{1,}\.jpg$

Result:

Pattern ^img_[a-zA-Z0-9]{1,}\.jpg$ matches "img_photo1.jpg" and "img_ABC.jpg" but rejects "photo.jpg" (missing prefix), "img_.jpg" (no characters between prefix and suffix), and "img_photo.jpeg" (wrong extension).

US ZIP Code Validation

Problem:

Accept both 5-digit ZIP codes and ZIP+4 codes (e.g., 12345 or 12345-6789) in an address form.

Solution Steps:

  1. 1Select "ZIP Code (US)" from the Common Patterns dropdown.
  2. 2The generator outputs: ^\d{5}(-\d{4})?$
  3. 3\d{5} requires exactly five digits.
  4. 4(-\d{4})? makes the hyphen-plus-four-digits group optional (the ? quantifier).
  5. 5The ^ and $ anchors ensure the entire value matches — no extra characters allowed.
  6. 6Test: "12345" → matches (basic ZIP); "12345-6789" → matches (ZIP+4); "1234" → fails (too short); "12345-67" → fails (incomplete ZIP+4).

Result:

Pattern ^\d{5}(-\d{4})?$ correctly accepts "12345" and "90210-1234" while rejecting partial or malformed codes.

Tips & Best Practices

  • Always test your regex with both valid examples that should match and invalid examples that should fail — one-sided testing misses half the bugs.
  • Use non-capturing groups (?:...) instead of capturing groups (...) when you only need grouping for structure, not back-references. This slightly improves performance and keeps match arrays clean.
  • Anchor full-string validation patterns with ^ and $ to prevent a short valid substring from passing validation inside a longer invalid input.
  • When building patterns for user-facing forms, provide a clear human-readable error message alongside the regex — a pattern like ^[a-zA-Z0-9]{3,16}$ should be paired with "Username must be 3–16 alphanumeric characters".
  • Store compiled regex patterns as constants or module-level variables rather than re-creating them inside loops or per-request functions to avoid unnecessary overhead.
  • The "Must Contain" field in the custom builder overrides the length constraints — if you need both a required substring AND a length limit, copy the generated pattern and manually add a length-checking lookahead like (?=.{5,20}).
  • Use regex101.com to interactively test and debug patterns — it highlights matched groups, explains each token, and shows all matches on a sample string in real time.
  • For phone number validation in international applications, consider using a dedicated library like libphonenumber rather than regex alone, since phone number formats vary enormously by country and change over time.
  • IPv4 patterns that only check digit ranges (like the built-in pattern) still accept valid-looking but reserved addresses like 0.0.0.0; pair regex validation with an IP parsing library if reserved-range rejection matters.

Frequently Asked Questions

By default, most regex engines look for the pattern anywhere within the input string — this is a substring or partial match. A full-string match requires the pattern to match the entire string from start to finish, which is enforced by adding the ^ anchor at the beginning and the $ anchor at the end. All patterns generated by this tool include both anchors, so they perform full-string validation. If you want to search for a pattern anywhere inside a larger document, remove the ^ and $ anchors.
Yes. Both React Hook Form and Formik accept a pattern validation rule that takes a RegExp object or string. For React Hook Form, pass the pattern as the value property inside the pattern rule object, along with a message property for the error text. For Yup (commonly used with Formik), use the .matches(regex, errorMessage) method on a string schema. Copy the pattern string from the generator and wrap it in new RegExp(pattern) or a regex literal /pattern/.
Characters like . + * ? ^ $ { } ( ) | [ ] \ have special meaning in regex syntax. If you type "v1.0" as a prefix, the unescaped dot would match any character (not just a literal period), so the tool automatically escapes it to "v1\.0". This ensures your literal text is matched exactly as typed. If you intentionally want to use a metacharacter in your prefix (e.g., a wildcard dot), you would need to edit the output pattern manually.
The patterns use a core subset of PCRE (Perl-Compatible Regular Expressions) syntax that is supported in JavaScript, Python, PHP, Java, C#, Go, and Ruby. Minor syntax differences exist at the edges: JavaScript regex literals do not need delimiters, while PHP wraps the pattern in delimiter characters. The string patterns shown in the generator (using double backslashes like \\d) are ready for use with string-based constructors; if you are writing a JavaScript regex literal, replace \\ with \. Always test in your target language.
The built-in email pattern covers the vast majority of real-world email addresses (local-part@domain.tld) but is intentionally simplified for practical validation rather than strict RFC 5321 compliance. The RFC technically allows edge cases like quoted strings, IP address literals, and certain special characters that almost no real email provider supports. The pattern will correctly validate common formats like user@example.com and john.doe+filter@sub.domain.co.uk while rejecting obviously invalid inputs.
Catastrophic backtracking occurs when a regex engine tries exponentially many paths through a pattern on certain inputs, causing the match to take seconds or minutes instead of microseconds. It is typically triggered by nested quantifiers like (a+)+ or alternation with overlapping branches applied to long strings. The built-in patterns on this page are designed to avoid this problem. If you write your own patterns that will process untrusted user input, test them with long strings of near-matching content and consider using a regex timeout or a safer pattern structure.
In JavaScript, append the i flag to your regex literal: /pattern/i, or pass "i" as the second argument to new RegExp(pattern, "i"). In Python, pass re.IGNORECASE (or re.I) as a flag to re.compile(). In PHP, append i after the closing delimiter: /pattern/i. When case-insensitivity is enabled, [a-z] automatically matches uppercase letters too, so you can simplify [a-zA-Z] to just [a-z] in the pattern.

Sources & References

Last updated: 2026-06-05

💡

Help us improve!

How would you rate the Regex Generator?

<>

Editorial Note

MyCalcBuddy Editorial Team

This page is maintained as an educational calculator reference.

Source

Formula Source: Standard Mathematical References

by Various

UpdatedLast reviewed: May 2026
CheckedFormula checks are based on standard references and internal QA review.