Skip to content

Regex for Password Strong — Pattern, Examples & Caveats

Pattern
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$

This pattern enforces a common strong-password policy: at least eight characters including a lowercase letter, an uppercase letter, a digit and a special character, using lookaheads to assert each requirement independently. Security-oriented patterns check sensitive or policy-bound input: password composition, card number shapes, tokens, private IP ranges and national identifiers. They are a first line of defense, never the whole story — pair them with checksums, real verification, encryption and access control. A regex can confirm a format but cannot prove a secret is valid or safe. It needs no special flags. Apply it to the whole input as a format contract. Composition rules like this are outdated guidance — NIST now favors length and breach screening over forced character classes; treat this as a legacy policy example. The . metacharacter does not match newlines by default, so passwords containing them fail; add the s flag if that is intentional. Lookaheads scan the whole string for each class, which is fine for short passwords but can be slow on very long inputs. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • (?=.*[a-z]) — lookahead requiring at least one lowercase letter
  • (?=.*[A-Z]) — lookahead requiring at least one uppercase letter
  • (?=.*\d) — lookahead requiring at least one digit
  • (?=.*[^A-Za-z0-9]) — lookahead requiring at least one non-alphanumeric character
  • .{8,} — at least eight characters total
  • ^...$ — anchors spanning the whole password

What it matches

Str0ng!PassAbcdef1@C0rrect-Horse!

What it does not match

alllowercase1!ALLUPPER1@NoDigits!!Sh0rt!OnlyLetters1

When to use it

Reach for a security pattern as one layer of input handling for sensitive or policy-bound data: password rules, card shapes, tokens, private ranges and national identifiers. Never treat a match as proof of validity or safety — combine it with checksums, signature verification, breach screening, encryption and strict access control. Also guard against ReDoS by avoiding nested quantifiers and bounding input length, since security checks are a tempting target for denial-of-service abuse.

Caveats

  • Composition rules like this are outdated guidance — NIST now favors length and breach screening over forced character classes; treat this as a legacy policy example.
  • The . metacharacter does not match newlines by default, so passwords containing them fail; add the s flag if that is intentional.
  • Lookaheads scan the whole string for each class, which is fine for short passwords but can be slow on very long inputs.

Code examples

JavaScript
const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
const input = "Str0ng!Pass";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$")
value = "Str0ng!Pass"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^A-Za-z0-9]).{8,}$");
Matcher m = p.matcher("Str0ng!Pass");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "Str0ng!Pass";
if (preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

Are forced character classes still recommended?

Modern guidance (NIST SP 800-63B) emphasizes minimum length, allowing all printable characters, and screening against breached passwords rather than mandating upper/lower/digit/symbol mixes.

How do I require a minimum of 12 characters instead?

Change .{8,} to .{12,}. The lookaheads stay the same; only the total-length quantifier controls the minimum.

Is a regex enough to secure sensitive input?

Never on its own. Regex checks format; security also needs checksums (Luhn), real verification (token signatures, breach screening), encryption, masking and access control. Treat the pattern as one layer, not the solution.

How do I prevent ReDoS in security checks?

Avoid nested unbounded quantifiers, set a match timeout where the engine supports it, cap input length, and prefer simple linear patterns. Test suspicious inputs with long non-matching strings before deploying.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →