CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
last occurance

 



sachin_perl
New User

Jun 10, 2013, 6:43 AM

Post #1 of 4 (11545 views)
last occurance Can't Post

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

Post #2 of 4 (11539 views)
Re: [sachin_perl] last occurance [In reply to] Can't Post

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


hwnd
User

Jun 11, 2013, 9:45 AM

Post #3 of 4 (11517 views)
Re: [Laurent_R] last occurance [In reply to] Can't Post

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

Post #4 of 4 (11500 views)
Re: [sachin_perl] last occurance [In reply to] Can't Post

.* 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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives