Regex Generator
Generate regular expression patterns from common rules or natural descriptions.
Generated Regex Pattern
A constrained builder is safer than pretending to understand prose
This regex generator builds a JavaScript-compatible pattern from explicit controls. It is not a natural-language model and it does not execute the result against sample text. Choose a preset for an email address, international-style phone number, or URL, or use Custom Pattern Builder to combine character categories, length quantifiers, and anchors. The generated body appears between visual slashes and Copy Regular Expression copies the pattern body itself.
The custom builder is intentionally narrow. It can express “a string of these character types with this total length,” but not separate requirements such as “must contain at least one digit and one symbol.” Those rules need lookaheads or, often more maintainably, separate application checks. Knowing the boundary prevents a plausible-looking pattern from enforcing the wrong policy.
All output targets JavaScript RegExp syntax. Other engines vary in anchors, Unicode classes, escapes, lookbehind, and flags. Test copied output in the exact runtime and API where it will run.
Decode each custom control
Include Letters contributes [a-zA-Z]. Include Numbers expands that to ASCII [0-9]. Selecting both yields [a-zA-Z0-9]. Include Special Characters/Spaces by itself yields [\W_], which means any JavaScript non-word character plus underscore. With all three options, the current implementation emits [a-zA-Z0-9\W].
These categories deserve scrutiny. JavaScript \W is the inverse of ASCII-oriented \w under ordinary semantics, so it includes whitespace, punctuation, many non-ASCII letters, line terminators, and other characters. “Special” is not a precise security category. If a product means a known punctuation set, replace broad \W with an explicit class such as [!@#$%], escaping ], -, ^, and backslash according to position.
The builder’s Case Insensitive state exists internally but has no rendered control and does not affect generated output. Copied patterns carry no flags. Add i in application code only if case-insensitive behavior is truly intended; [a-zA-Z] already contains both ASCII cases.
If no character checkbox is selected, the body becomes dot (.). In JavaScript without the s flag, dot does not match line terminators. It does not mean “any byte,” and it can split Unicode surrogate pairs without Unicode mode.
Min Length and Max Length select a quantifier:
- Minimum 1 with blank maximum emits
+, meaning one or more. - Minimum 0 with blank maximum emits
*, meaning zero or more. - Equal numeric minimum and maximum emit
{n}. - Other combinations emit
{min,max}or{min,}when maximum is blank and minimum is above 1.
The UI does not reject every invalid relationship. A maximum below the minimum can create a syntax error, negatives are inappropriate, and blank or non-numeric minimum is interpreted as zero. Review and test the result rather than assuming form controls prove validity.
Start Anchor (^) and End Anchor ($) decide whether the pattern validates a whole input or searches within it. Both enabled is typical for a form field. With either disabled, a valid substring can make an otherwise invalid value match. Under the multiline m flag, anchors can match line boundaries inside an input, so do not add that flag casually to a whole-field validator.
Worked custom examples
For an ASCII customer code containing only uppercase or lowercase letters and digits, length 8 through 12:
- Choose Custom Pattern Builder.
- Enable Letters and Numbers; disable Special.
- Set minimum 8 and maximum 12.
- Keep both anchors enabled.
The result is:
^[a-zA-Z0-9]{8,12}$
It accepts Abc902xy and rejects abc-902, but it does not guarantee both a letter and a number. If that is a business requirement, validate category presence separately or extend carefully:
^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{8,12}$
For a numeric database code exactly six characters long, select Numbers only, set both lengths to 6, and retain anchors. The resulting ^[0-9]{6}$ treats leading zeroes correctly when the input remains a string. It is not a secure one-time password generator and does not validate whether the code was issued.
For free-form text between 1 and 80 characters, selecting no categories produces ^.{1,80}$. That rejects line breaks and counts JavaScript UTF-16 code units, not grapheme clusters users perceive as characters. A family emoji, combining accent, or supplementary character can make UI length differ. Use application-level Unicode length logic when user-visible character counts matter.
Evaluate the presets as starting points
The Email Address preset checks a conventional ASCII local part, an @, domain-like labels, and an alphabetic suffix of at least two characters. It does not implement every valid RFC mailbox, internationalized address, quoted local part, domain-label rule, or deliverability check. A practical signup flow performs modest shape validation, caps length, normalizes the domain where appropriate, and sends a verification email.
The Phone Number (International) preset allows an optional plus, one to three initial digits, optional separators, optional parentheses around a three-digit section, then three and four digits. It assumes a particular grouping and can accept inconsistent formatting. Phone numbering plans are country-specific; use a maintained phone-number parser such as libphonenumber when normalization or validity matters, then verify ownership through a code.
The URL Link preset recognizes HTTP or HTTPS strings with a domain-like host and optional path characters. URL grammar includes internationalized hosts, IPv6 literals, ports, user information, percent escapes, and scheme-specific behavior that one compact regex handles poorly. Parse with new URL(), restrict protocols explicitly, normalize hostnames, and defend separately against server-side request forgery if the server fetches the URL.
Presets replace the custom controls rather than combining with them. The output shows delimiters for readability, but the copy action writes only pattern, not /pattern/ or flags. That is convenient for new RegExp(copiedPattern) and configuration fields; a regex literal in source needs surrounding slashes and escaped literal slash characters.
From generated pattern to tests
Take ^[a-zA-Z0-9]{8,12}$ and create a table:
| Input | Expected | Reason |
|---|---|---|
Abc902xy |
match | minimum length, allowed set |
Abc902xyZZZZ |
match | maximum length |
Abc902x |
no match | too short |
Abc902xyZ0000 |
no match | too long |
Abc-02xy |
no match | hyphen excluded |
ébc902xy |
no match | ASCII letters only |
Abc902xy\n |
inspect | end-anchor and API behavior |
Run those cases in the production JavaScript version. Test both positive and near-miss input; a handful of happy examples cannot establish correctness. When embedding the body in a JavaScript string, JSON, YAML, HTML attribute, shell command, or database query, account for that layer’s escaping. Regex escapes and host-language escapes are separate.
For server validation, enforce an input-size ceiling before regex evaluation. Anchored simple character classes are usually predictable, but later manual edits can add ambiguous alternation or nested quantifiers. Benchmark long failing strings and review for Regular Expression Denial of Service. Client validation improves feedback but must be duplicated or replaced by authoritative server validation.
Semantics regex should not own
A date pattern can constrain YYYY-MM-DD shape and rough ranges but should not decide leap years or whether February has 30 days. A parser can. A password regex should not estimate entropy, detect breach reuse, hash credentials, or impose every policy through stacked lookaheads. An HTML regex should not sanitize markup; use a reviewed parser and sanitizer.
Matching allowed characters also does not make data safe to interpolate into SQL, HTML, shell commands, paths, or URLs. Use parameterized queries and contextual escaping. Regex validation is not authorization, canonicalization, encryption, or encoding.
If the accepted language is small, document it in plain terms beside the pattern. Future maintainers can compare intent with implementation. Named constants and table-driven tests are easier to review than a dense expression copied without provenance.
Typical builder mistakes
- Selecting Special Characters to mean punctuation, then unintentionally allowing spaces and newlines through
\W. - Omitting anchors and accepting a valid substring inside invalid text.
- Expecting Letters plus Numbers to require at least one of each.
- Copying the visual slashes into a
RegExpconstructor value. - Adding an
iflag even though explicit[a-zA-Z]already covers ASCII case. - Using regex to parse URLs, dates, email delivery, or phone plans beyond its suitable structural role.
- Forgetting that JavaScript length and indexes use UTF-16 code units.
FAQ
How do I generate a regex for letters and numbers only?
Enable Letters and Numbers, disable Special, choose lengths, and keep both anchors for whole-input validation. The body uses [a-zA-Z0-9].
Why does my generated password regex allow all letters?
Category selection defines allowed characters, not mandatory categories. Add separately tested lookaheads or perform clear application-level checks for required classes.
Does Special Characters exclude whitespace?
No. The generated \W includes whitespace and many non-ASCII characters. Replace it with an explicit punctuation class when whitespace must be forbidden.
Are regex flags copied with the pattern?
No. The tool copies the pattern body. Supply flags separately in the target API.
Can I trust a preset as complete validation?
Treat presets as editable starting points. Use domain parsers and real verification workflows for email, phone, and URL semantics, and preserve regression cases for your actual policy.