Last update:   29-10-2021

Look ahead

Looks ahead in the text (toward the right) to see if its subexpression can match. Positive lookahead is successful at positions where a digit comes next. Positive lookbehind is successful at positions with a digit to the left.
(?=\d) // look ahead

(?<=\d) // look behind
Position Or Location    (2/4)

Position or location

Is important to understand is that the lookaround don't actually "consume" any text. The regex /Jeffrey/ matches Jeffrey in "Jeffrey Friedl". The regex lookahead, (?=Jeffrey) matches only the location (position) before Jeffrey. The order in which they're combined is very important.
Jeff(?=Jeffrey) // doesn't match by Jeffrey Friedl

Jeff(?=Jeffrey) //matches "Jeff" if followed immediately by Jeffrey
Lookaround Types    (3/4)

Lookaround types

We've already seen group-but-don't-capture (?: ), lookahead (?= ), lookbehind (?<= ). Positive Lookahead (?= ) successful if can MATCH to the RIGHT Positive Lookbehind (?<= ) successful if can MATCH to the LEFT Negative Lookahead (?! )}} successful if can NOT match to the RIGHT Lookaround Examples    (4/4)

Lookaround examples

1) Matches "Jeff" only if it is part of "Jeffrey"
$var = "Jeffrey Friedl";
$var =~ s/(?=Jeffrey)(Jeff)/by $1/;
print $var; #Outpus: by Jeffrey Friedl // Jeff Friedl doesn't match
2) Replace "Jeffs" with "Jeff's"
// with lookahead
$var = "Jeffs articles";
$var =~ s/\bJeff(?=s\b)/Jeff'/g;
print $var; // Outputs: Jeff's articles

// with lookbehind
$var = "Jeffs articles";
$var =~ s/(?<=\bJeff)(?=s\b)/'/g;
print $var; // Outputs: Jeff's articles
... 3 lines
3) Commafying numbers
$var = "The population of 2298444215 is growing";
$var =~ s/(?<=\d)(?=(\d\d\d)+)/,/g;
print $var . "\n"; //Outputs: 2,2,9,8,4,4,4,215

// If we add \b it works

$var = "The population of 2298444215 is growing";
$var =~ s/(?<=\d)(?=(\d\d\d)+\b)/,/g;
print $var . "\n"; //Outputs: 2,2,9,8,4,4,4,215

// But it doesn't match something like:

$var = "12345Hz";
$var =~ s/(?<=\d)(?=(\d\d\d)+\b)/,/g;
print $var . "\n"; //Outputs: 12345Hz

// We use (?!\d) as three digits boundary

$var = "12345Hz";
$var =~ s/(?<=\d)(?=(\d\d\d)+(?!\d))/,/g;
print $var . "\n"; //Outputs: 12,345Hz
... 9 lines


        A B C D E F