Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searing from Left to Right?

Status
Not open for further replies.

mikedaruke

Technical User
Mar 14, 2005
199
0
0
US
I have a string

$string = 'I_Love_Perl_So_Much';

I want to capture the 'Much' word, or the last match for
_.*?$

I am currently doing

$string =~ m/_(.*?)/;

but it finds _Love_Perl_So_Much

How can I get perl to search from the Left to the Right instead of Right to Left?

Thanks
 
The problem is with your regular expression. You are asking it to find anything after and including an underscore, but what you want is to find anything after the last underscore. I'm not really practiced with regex, but I think you need to do a greedy match instead of a minimal one. This might work, though I think it will still return the leading underscore: m/_(.*)$/
 
Doesn't work, it still goes from the first _ rather then the last one.
 
Perhaps
Code:
$str = "we_all_love_perl";
$str =~ /_([^_]+)$/ ;
print $1 . "\n";

This may not be efficient but how about:
Code:
$str = "we_all_love_perl";
(reverse $str) =~ /^([^_]*)_/ ;
$match = reverse $1 ;
print $match . "\n";
 
or
Code:
$str = "we_all_love_perl";
$match = (split(/_+/, $str))[-1] ;
print $match . "\n";

... or
Code:
$str = "we_all_love_perl";
$str =~ s/.*_//g ;
print $str . "\n";

.. or
 
I'd go with this suggestion:

$str =~ /_([^_]+)$/;





------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top