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:
Substituting // for last match in a string

 



rwb2314460
Novice

Aug 29, 2002, 10:18 AM

Post #1 of 4 (3665 views)
Substituting // for last match in a string Can't Post

I need to be able to strip off the last underscore and everything that follows that character.
For example if I have the string
"text_text_20020829.dat"
I want to be returned the string
"text_text".

Or if I have the string
"text_20020829.dat"
I want to be returned the string
"text".

Any assistance would be appreciated.

Thanks,
Bob


Paul
Enthusiast

Aug 29, 2002, 10:53 AM

Post #2 of 4 (3662 views)
Re: [rwb2314460] Substituting // for last match in a string [In reply to] Can't Post


Code
my $var = 'abc_123_def.dat'; 

$var = substr($var, 0, rindex($var, '_'));


I know it isn't a regex but it may be a bit quicker :)

But if you need case insensitivity or something use:


Code
$file =~ s/_.*$//i;



(This post was edited by RedRum on Aug 29, 2002, 10:55 AM)


davorg
Thaumaturge / Moderator

Aug 30, 2002, 9:10 AM

Post #3 of 4 (3645 views)
Re: [RedRum] Substituting // for last match in a string [In reply to] Can't Post


Code
$file =~ s/_.*$//i;

That doesn't work if there is more than one _ in the string.


Code
$_ = "text_text_20020829.dat"; 

s/_.*$//i;

print; # prints "text"


Try this instead.

Code
s/_[^_]*$//i;


But you're right that the substr/rindex solution is probably faster.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


Paul
Enthusiast

Aug 30, 2002, 9:13 AM

Post #4 of 4 (3644 views)
Re: [davorg] Substituting // for last match in a string [In reply to] Can't Post

Whoops I forgot the ? but I should have used [^_]* anyway.


(This post was edited by RedRum on Aug 30, 2002, 9:13 AM)

 
 


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

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