view raw
hampadampadoo hampadampadoo - 8 months ago 39
Perl Question

lookahead in the middle of regex doesn't match

I have a string

$s1 = "a_b";
and I want to match this string but only capture the letters. I tried to use a lookahead:

if($s1 =~ /([a-z])(?=_)([a-z])/){print "Captured: $1, $2\n";}

but this does not seem to match my string. I have solved the original problem by using a
instead, but I am curious to why my original attempt did not work? To my understanding a lookahead matches but do not capture, so what did I do wrong?


A lookahead looks for next immediate positions and if a true-assertion takes place it backtracks to previous match - right after a - to continue matching. Your regex would work only if you bring a _ next to the positive lookahead ([a-z])(?=_)_([a-z])

You even don't need (non-)capturing groups in substitution:

if ($s1 =~ /([a-z])_([a-z])/) { print "Captured: $1, $2\n"; }