Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl regex match closest

I'm trying to match from the last item closet to a final word.

For instance, closest b to dog

"abcbdog"

Should be "bdog"

But instead I'm getting "bcbdog"

How can I only match from the last occurrence "b" before "dog"

Here is my current regex:

/b.*?dog/si

Thank you!

like image 210
srchulo Avatar asked Dec 16 '22 08:12

srchulo


2 Answers

Regexes want to go from left to right but you want to go from right to left so just reverse your string, reverse your pattern, and reverse the match:

my $search_this  = 'abcbdog';
my $item_name    = 'dog';
my $find_closest = 'b';

my $pattern = reverse($item_name)
            . '.*?'
            . reverse($find_closest);

my $reversed     = reverse($search_this);
$reversed        =~ /$pattern/si;
my $what_matched = reverse($&);
print "$what_matched\n";
# prints bdog
like image 143
mu is too short Avatar answered Jan 15 '23 06:01

mu is too short


Try this:

/b[^b]*dog/si

Match b, then anything that isn't a b (including nothing), and then dog.

like image 33
James Sneeringer Avatar answered Jan 15 '23 07:01

James Sneeringer