Combining Multiple Assertions
You'll learn how to chain multiple lookaheads, lookbehinds, and anchors together to create surgical-precision matching conditions.
The Power of Layered Assertions
Think of assertions like security checkpoints at an airport—each one checks a different requirement, and all must pass for someone to proceed. In regex, you can stack multiple lookaheads, lookbehinds, and anchors at the same position to enforce several conditions simultaneously.
The key insight: assertions are zero-width. They don't consume characters, so you can place multiple assertions back-to-back, and they'll all check the same position in the string.
Practical Combinations
Multiple lookaheads for complex validation:
// Password must have: uppercase, lowercase, digit, and be 8+ chars
const strongPass = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/;
console.log(strongPass.test('Abc12345')); // true
console.log(strongPass.test('abc12345')); // false (no uppercase)
Mixing lookahead and lookbehind:
// Match "test" only if preceded by "unit " and followed by " passed"
const pattern = /(?<=unit )test(?= passed)/;
console.log(pattern.test('unit test passed')); // true
console.log(pattern.test('unit test failed')); // false
Combining negative and positive assertions:
// Match words that start with vowel but NOT followed by "x"
const pattern = /\b[aeiou]\w*(?!x\b)/gi;
const text = 'apple ox index eagle';
console.log(text.match(pattern)); // ['apple', 'index', 'eagle']
// 'ox' excluded by negative lookahead
Anchors with assertions:
// Email-like pattern: starts with word chars, has @, ends with domain
const email = /^(?=.*@)[\w@.]+(?<=\.com)$/;
console.log(email.test('user@site.com')); // true
console.log(email.test('user@site.org')); // false
Key Takeaway: Stack multiple assertions at the same position to create complex validation rules—each assertion acts as an independent filter that the match must pass through.