Here’s a clear, easy-to-use guide to positive lookahead assertions in regular expressions:
✅ What is a Positive Lookahead?
A positive lookahead checks whether a certain pattern comes after the current position — without including it in the match.
The syntax is:
(?=pattern)
Think of it as saying:
“Match this… only if it is followed by that.”
Lookaheads are zero-width assertions — they do not consume characters. They only peek ahead.
π Simple Example
Match the word cat only when followed by s
Regex:
cat(?=s)
Text:
cats cat catapult scatter
Matches:
cat (in cats)
Not these:
cat (alone)
cat (in catapult)
Because only the first cat is directly followed by s.
π Practical Uses
1️⃣ Ensure a password contains a number
Regex:
^(?=.*[0-9]).+$
Meaning:
(?=.*[0-9])→ somewhere ahead, there must be a digit.+→ match the whole string
2️⃣ Match emails from a specific domain
Match username only if followed by @gmail.com
.+(?=@gmail\.com)
Text:
alex@gmail.com
sam@yahoo.com
Matches only:
alex
3️⃣ Match a word only when followed by punctuation
word(?=[.!?])
Matches word in:
word! word? word.
But not in:
word is here
π Compare: Positive vs Negative Lookahead
| Type | Syntax | Meaning |
|---|---|---|
| Positive Lookahead | (?=...) | Must be followed by… |
| Negative Lookahead | (?!...) | Must not be followed by… |
Example negative:
cat(?!s)
Means “cat not followed by s”.
π‘ Key Things to Remember
Lookaheads do not consume characters
They work at the same position
They can be combined
Supported in most engines (JS, Python, PCRE, etc.)
π§ͺ Example in JavaScript
const regex = /cat(?=s)/g;
console.log("cats cat".match(regex));
// Output: ["cat"]
π§ͺ Example in Python
import re
print(re.findall(r"cat(?=s)", "cats cat"))
# Output: ['cat']
Enjoy! Follow us for more...


No comments:
Post a Comment