Perl (Scripting) - match first all last occurrence of a pattern

by
Jeremy Canfield |
Updated: March 22 2022
| Perl (Scripting) articles
Let's say you have the following Perl script.
#!/usr/bin/perl
use strict;
use warnings;
my $string = "foo bar foo bar foo bar";
print "$string \n";
Running this script should return the following.
foo bar foo bar foo bar
The following regular expression will match the first occurrence of "foo".
$string =~ s|foo||;
Which should return the following.
bar foo bar foo bar
The g (global) flag should match every occurrence of "foo".
$string =~ s|foo||g;
Which should return the following.
bar bar bar
A negative lookahead can be used to match the last occurrence of "foo".
$string =~ s|foo(?!.*foo)||;
Which should return the following.
foo bar foo bar bar
A different approach is needed when you want to match everything until the first occurrence of a pattern is found. The following will match everything until the first occurrence of bar is found.
$string =~ s|^([^bar]+)||;
Which should return the following.
bar foo bar foo bar
Did you find this article helpful?
If so, consider buying me a coffee over at