Download Video : What is positive lookahead assertions in regular expressions.mp4
Positive lookahead in regular expressions is a zero-width assertion that checks whether a certain pattern follows the current position — without including it in the match.
It’s written like this:
(?=...)
Whatever goes inside ... must be true for the match to succeed — but it is not consumed as part of the match.
🧠 Key idea
Think of it as saying:
“Match this… only if it is followed by that.”
But we don’t actually capture that in the final result.
✅ Simple example
Pattern:
\d(?=px)
Text:
5px 10pt 8px
Matches:
5
8
Explanation:
\d→ match a digit(?=px)→ only if it is immediately followed by the letterspx
So it matches the 5 in 5px and the 8 in 8px, but not the 10 in 10pt, because that digit is not followed by px.
💡 Another example — match words followed by !
Pattern:
\w+(?=!)
Text:
Wow! Amazing! Nice
Matches:
Wow
Amazing
The lookahead checks for ! but doesn’t include it in the match.
🔍 Important properties
Zero-width — it does not consume characters
Does NOT capture the lookahead text
Only checks what comes next
🚫 Contrast: Negative lookahead
Positive lookahead:
(?=...)
means must be followed by ...
Negative lookahead:
(?!...)
means must NOT be followed by ...
Example:
foo(?!bar)
matches foo only when it is NOT followed by bar.
📌 Common real-world uses
✔ Validate password rules
✔ Ensure a word is followed by another
✔ Match text before certain patterns
✔ Conditional matching without consuming text
Example — password must include a digit:
^(?=.*\d).+$
Meaning:
(?=.*\d)→ there must be at least one digitthe rest just matches the password
📝 Summary
Positive lookahead:
| Feature | Description |
|---|---|
| Syntax | (?=...) |
| Purpose | Ensure pattern follows |
| Consumes text? | ❌ No |
| Captures text? | ❌ No |
| Works like | A condition |


No comments:
Post a Comment