Regex Lookbehind

Created with Sketch.

Regex Lookbehind

Summary: in this tutorial, you’ll learn about the regex lookbehind and negative lookbehind.

Introduction to the regex lookbehind

Suppose you have the following string:

'2 chicken cost $40';

Code language: JavaScript (javascript)

And you want to match the number 40 after the $ sign but not the number 2. To do that, you use a lookbehind. A lookbehind matches an element only if there’s an element before it.

Like the lookahead, the lookbehind has the following syntax:

(?<=B)A

 

This pattern matches A if there is B before it.

The following example uses a lookbehind to match a number that has the $ sign before it:

<?php

$pattern = '/(?<=\$)\d+/';
$str = '2 chicken cost $40';

if (preg_match($pattern, $str, $matches)) {
print_r($matches);
}

Code language: HTML, XML (xml)

Output:

Array
(
[0] => 40
)

Code language: PHP (php)

In the following regular expression:

'/(?<=\$)\d+/'

Code language: JavaScript (javascript)

  • The (?<=\$) is the lookbehind that matches the following has the $ sign. Since $ has a special meaning in the pattern, you need to escape it using the backslash (\).
  • The \d+ matches a number with one or more digits.

The regular expression matches a number that has the $ before it.

Negative lookbehind

The negative lookbehind has the following syntax:

(?<!B)A

 

It matches A if there’s no B before it.

The following example uses a negative lookbehind to match a number that doesn’t have the $ sign before it:.`

<?php

$pattern = '/(?<!\$)\d+/';
$str = '2 chicken cost $40';

if (preg_match($pattern, $str, $matches)) {
print_r($matches); // 40

}

Code language: PHP (php)

Output:

Array
(
[0] => 2
)

Code language: PHP (php)

In the regular expression:

'/(?<!\$)\d+/'

Code language: JavaScript (javascript)

  • The (?<!\$) is a negative lookbehind that does not match the $ sign.
  • The \d+ matches a number with one or more digits.

Summary

  • A lookbehind (?<!B)A matches A only if there’s B before it.
  • A negative lookbehind (?<!B)A matches A only if there’s no element before it.

Leave a Reply

Your email address will not be published. Required fields are marked *