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!
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
Try this:
/b[^b]*dog/si
Match b
, then anything that isn't a b
(including nothing), and then dog
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With