Lookahead
Every pattern so far consumes what it matches - the matched text becomes
part of the result. A lookahead , (?=...), is different: it checks that
something comes next without consuming it. /cat(?= food)/ only matches
"cat" when it's immediately followed by " food" - but the match itself is
still just "cat", not "cat food".
Lookahead is also how you check "does this string contain X somewhere "
without pinning down exactly where. /^(?=.*\d)/ reads as: from the start,
look ahead for .*\d (anything, then a digit) - true if a digit exists
anywhere in the string, even though the lookahead itself matches zero
characters. This is the trick behind password rules like "must contain a
digit" - no loop, no scanning code, just a position check.
Your task: write matchCatFood(str), returning "cat" if str contains
"cat" immediately followed by " food" (without including " food" in the
result), or null otherwise; and hasDigitSomewhere(str), true if str
contains a digit anywhere.
You'll practice:
Asserting what comes next with (?=...) without consuming it
Using a lookahead to check "contains X somewhere" in one pattern
Show a hint
Show solution
Previous Next