مرکزی مواد پر جائیں
eLearner.app
ماڈیول 6 · سبق 3 از 4کورس میں 23/32~12 min
ماڈیول اسباق (3/4)

پیچھے دیکھو: `(?<=...)` (?<!...)`

Lookbehinds are the mirror image of lookaheads: they look before the current position, still zero-width.

  • (?<=...) -- positive lookbehind: the pattern must precede.
  • (?<!...) -- negative lookbehind: the pattern must NOT precede.
Code
Pattern: (?<=\$)\d+
Sample:  Costo $100, sconto -25, totale $75.
                ^^^                  ^^

The $ is not in the match, but works as a condition: only digits preceded by the dollar sign match.

Negative lookbehind

Code
Pattern: (?<!\w)\d+
Sample:  Codice abc123 e numero 456.
                              ^^^

(?<!\w) requires that before the digits there be NO word character: abc123 is excluded (before 123 there is c, a \w), 456 matches (before there is a space).

Key difference vs non-capturing group

Code
\\$\\d+         matches "$100": the match includes the dollar sign.
(?<=\\$)\\d+    matches "100":  the match contains ONLY the digits.

If you need to extract the "clean" value without the prefix, lookbehind is the right choice.

Lookbehind compatibility in JavaScript

Positive (?<=...) and negative (?<!...) lookbehind check what precedes the current position. In JavaScript, they are supported starting from ES2018; in older browsers or legacy Node.js engines, they would cause syntax compilation errors.

Try it

ورزش#regex.m6.l3.e1
کوششیں: 0لوڈ ہو رہا ہے…

Extract only the numeric amount (without the $ sign) from the prices in the text.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Move \\$ inside a positive lookbehind (?<=\\$): a position condition, not part of the match.

3 کوششوں کے بعد حل دستیاب ہے۔

Review exercise

ورزش#regex.m6.l3.e2
کوششیں: 0لوڈ ہو رہا ہے…

Find every sequence of digits NOT preceded by a letter or digit (i.e., 'isolated' numbers, not parts of code like `abc123`).

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Use a negative lookbehind (?<!\\w) to exclude when there is a letter or digit before.

3 کوششوں کے بعد حل دستیاب ہے۔

Additional challenge

ورزش#regex.m6.l3.e3
کوششیں: 0لوڈ ہو رہا ہے…

Find only the digits of negative numbers (digits preceded by the `-` sign), excluding the minus sign from the match.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Move the minus sign - inside a positive lookbehind (?<=-).

3 کوششوں کے بعد حل دستیاب ہے۔