What is positive lookahead assertions in regular expressions .

 



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 letters px

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 digit

  • the rest just matches the password


📝 Summary

Positive lookahead:

FeatureDescription
Syntax(?=...)
PurposeEnsure pattern follows
Consumes text?❌ No
Captures text?❌ No
Works likeA condition


No comments:

Post a Comment

How to Link CSS and JavaScript files to your HTML file.mp4

  Download Video:  How to Link CSS and JavaScript files to your HTML file.mp4 ✅ 1. Linking a CSS file to HTML CSS controls the styling and l...