Home: Perl Programming Help: Regular Expressions:
last occurance



sachin_perl
New User

Jun 10, 2013, 6:43 AM


Views: 23198
last occurance

Hi,
I am looking for a regex which should find the last occurance of a expression like
I have to find last PM(/d+)*.xml in a file
t1.txt
ggdt 2365 237 PM23jhfy&%_kkf.xml wknw f
wef ^& 8* uy y w9 8y
ivhodio wroio wroi icvo PM12_uryt&^%_uieg.xml uet.

But this is finding the first PM*.xml.
I also tried .*PM(/d+)*.xml but getting the first one. Please help


Laurent_R
Veteran / Moderator

Jun 10, 2013, 9:11 AM


Views: 23192
Re: [sachin_perl] last occurance

Reverse the file order and look for the first one. ;-)


hwnd
User

Jun 11, 2013, 9:45 AM


Views: 23170
Re: [Laurent_R] last occurance

So you just need the numbers from the last occurence of PM? Or the whole PM .. .xml line?


Quote
I have to find last PM(/d+)*.xml in a file



Seeing how you said find last occurrence in a file, I'm assuming these are lines in a file. So therefore here are a few examples, not clear exactly if you are just wanting the digits from the last occurrence or the whole line.


Code
__DATA__  

ggdt 2365 237 PM23jhfy&%_kkf.xml wknw f
wef ^& 8* uy y w9 8y
ivhodio wroio wroi icvo PM12_uryt&^%_uieg.xml uet.



If you want last occurrence of digits, you could do this.


Code
open my $fh, '<', 'file.txt' or die "failed: $!"; 
my ($str) = map { $_ =~ /.*(?:PM)(\d+)/ } reverse <$fh>;
close $fh;

print $str;


__OUTPUT__

12



If you want the whole line including .xml you could do this.


Code
open my $fh, '<', 'file.txt' or die "failed: $!"; 
my ($str) = map { $_ =~ /.*(PM.*\.xml)/; } reverse <$fh>;
close $fh;

print $str;

__OUTPUT__

PM12_uryt&^%_uieg.xml



(This post was edited by hwnd on Jun 11, 2013, 5:14 PM)


BillKSmith
Veteran

Jun 11, 2013, 2:54 PM


Views: 23153
Re: [sachin_perl] last occurance

.* is "greedy".


Code
use strict; 
use warnings;
my $filename
= "ggdt 2365 237 PM23jhfy&%_kkf.xml wknw f\n"
. "wef ^& 8* uy y w9 8y\n"
. "ivhodio wroio wroi icvo PM12_uryt&^%_uieg.xml"
;

my ($digits) = $filename =~ m/.*PM(\d+).*\.xml/ms;
print $digits;


Output: 12
Good Luck,
Bill