Regex Lookaheads: Check Multiple Words Without Verbose Permutations

📖 1 minute read

Need to validate that a string contains multiple words in any order? Don’t write 6 permutations of the same regex. Use positive lookaheads instead.

The Problem

You want to check if a string contains “cat” AND “dog” AND “bird” in any order. The naive approach is a mess of permutations — 6 for 3 words, 24 for 4 words. No thanks.

The Fix: Chained Positive Lookaheads

$pattern = '/^(?=.*cat)(?=.*dog)(?=.*bird)/';
$text = 'I saw a bird, then a cat, then a dog';

if (preg_match($pattern, $text)) {
    echo 'All three words found!';
}

Each (?=.*word) is a separate assertion. All must pass. Order doesn’t matter. Add a fourth word? Add one more lookahead. Clean and scalable.

Takeaway

Positive lookaheads let you check multiple conditions without caring about order. Use (?=.*word) for each required word. Works in PHP, JavaScript, Python — basically everywhere.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *