Password validation

2 snippets in Regular Expressions

RXRegular Expressions

Combining Lookaheads & Lookbehinds

RX · Lookahead & Lookbehind
Syntax
(?<=prefix)pattern(?=suffix)
Example
JS:  'price: [42] and size: [XL]'.match(/(?<=\[)\d+(?=\])/g)
Py:  re.findall(r'(?<=\[)\w+(?=\])', '[hello] and [world]')
Output
JS: ["42"]  (digits inside square brackets, without brackets)
Py: ["hello", "world"]

Note You can combine multiple lookarounds on the same position. A common pattern for password validation stacks multiple lookaheads: (?=.*[A-Z])(?=.*\d)(?=.*[@#$]).{8,} checks for uppercase, digit, and special character all in one pass.

Stacked Lookaheads for Validation

RX · Lookahead & Lookbehind
Syntax
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%]).{8,}$
Example
JS:  const strong = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%]).{8,}$/
     strong.test('MyP@ss1word')   // true
     strong.test('weakpass')       // false
Py:  pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%]).{8,}$'
     bool(re.match(pattern, 'MyP@ss1word'))  # True
Output
true / True for 'MyP@ss1word', false / False for 'weakpass'

Note Each lookahead checks a different requirement without advancing the match position. All must pass before .{8,} consumes the string. This is a widely-used pattern but be cautious about catastrophic backtracking with very long inputs -- consider checking each requirement separately in code for production validation.

Frequently asked questions

How does Regular Expressions handle password validation?
Regular Expressions covers this with 2 copy-ready snippets on this page. The "Combining Lookaheads & Lookbehinds" snippet in Regular Expressions uses `(?<=prefix)pattern(?=suffix)`.
Which pattern does the Regular Expressions example use?
The "Combining Lookaheads & Lookbehinds" snippet uses `(?<=prefix)pattern(?=suffix)`, from the Lookahead & Lookbehind section of the Regular Expressions cheat sheet.
What other Regular Expressions snippets are shown for "password validation"?
Besides "Combining Lookaheads & Lookbehinds", this page also shows "Stacked Lookaheads for Validation".
Is there anything to watch out for?
Yes. For "Combining Lookaheads & Lookbehinds": You can combine multiple lookarounds on the same position. A common pattern for password validation stacks multiple lookaheads: (?=.*[A-Z])(?=.*\d)(?=.*[@#$]).{8,} checks for uppercase, digit, and special character all in one pass.