ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 6 · 4లో పాఠం 2కోర్సులో 22/32~10 min
మాడ్యూల్ పాఠాలు (2/4)

ప్రతికూల దృష్టి: `(?!...)`

The negative lookahead (?!...) is the dark sister of the positive lookahead: it requires that the given pattern NOT follow the current position. It is still zero-width: no character is consumed.

Code
Pattern: \d+(?! euro)
Sample:  Prezzo 100 euro, sconto 25 euro, totale 75 dollari.
                                          ^^

Only 75 matches, because it is the only sequence of digits NOT followed by euro. The digits 100 and 25 are followed by euro and are excluded.

Typical negative lookahead patterns

  • ^(?!.*errore).*$ -- a line that does NOT contain the word "errore".
  • \b(?!the\b)\w+\b -- a word that is not the.
  • (?!\s) -- the current position is NOT a whitespace (useful as a "trim").
Code
Pattern: ^(?!.*\.bak$).*$
Sample (multiline with flag m):
  foto.jpg
  backup.bak
  documento.txt
Match: foto.jpg, documento.txt (excludes backup.bak)

Advanced exclusions via negative lookahead

The negative lookahead (?!...) is essential for implementing exclusion logic (like verifying that a password does not contain dictionary words or that an identifier is not a reserved keyword like class or function).

Try it

వ్యాయామం#regex.m6.l2.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find every number NOT followed by ' euro' (so excluding the euro prices).

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use (?! ...) to say 'must NOT follow'. The ` euro` sequence must not appear after.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#regex.m6.l2.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find every word of at least 3 letters that is NOT 'the' (case-insensitive).

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Right after \\b open a negative lookahead (?!the\\b) that excludes only the word the.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Additional challenge

వ్యాయామం#regex.m6.l2.e3
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find all words consisting of letters that do not contain the letter `x` at any position (e.g. match `test`, `game` but not `extra`, `box`).

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use a negative lookahead (?!\w*x) right after the word boundary \b.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది