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

Updated:   |  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

 

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 Buy Me A Coffee



Comments


Add a Comment


Please enter 63e28c in the box below so that we can be sure you are a human.