siddheshsawant has asked for the wisdom of the Perl Monks concerning the following question:

Hello friends , I have a string which is URL like this:

"http://192.162.143.201/nightly_results/2009_12_02/log_lcla114.ping.com_64.html"

I wants to extract only "log_lcla114.ping.com_64.html" out of above whole string..I tried to extract it but I couldnot able to get success..My code and corresponding output is as follows

#!/usr/bin/perl -w use strict; my $mystring = "http://192.162.143.201/nightly_results/2009_12_02/log_ +lcla114.ping.com_64.html"; if($mystring =~ m!([^/]+)!){ my $file=$1; print "field= $file\n"; }

I got output like this:

field= http:

where as I expect to get "log_lcla114.ping.com_64.html" can anybody rectify my regex to get desired output....Thanks in advance !!!!!

Replies are listed 'Best First'.
Re: A question on Regex
by ssandv (Hermit) on Mar 24, 2010 at 19:43 UTC
    you need to anchor it to the end of line, like so:
    if($mystring =~ m!([^/]+$)!){ #note the $ character added
Re: A question on Regex
by kennethk (Abbot) on Mar 24, 2010 at 19:44 UTC
    The regular expression is capturing the first string it encounters that does not contain a slash. That first string is "http:". Assuming you actually want to capture the last one, you can use the $ metacharacter to anchor the regular expression to the end of the string:

    if($mystring =~ m!([^/]+)$!){

    More information on metacharacters can be found in Regular Expressions in perlre or Simple word matching in perlretut.

      ohh ya I have to anchor it ....thanks a lot for your suggestion !!!!!

Re: A question on Regex
by Your Mother (Archbishop) on Mar 24, 2010 at 19:53 UTC

    A non-regex way. This is overkill for one-offs but you can see it's actually quite terse and grows well. URI and Path::Class.

    use URI; use Path::Class; my $uri = URI->new("http://192.162.143.201/nightly_results/2009_12_02/ +log_lcla114.ping.com_64.html"); my $path = Path::Class::File->new($uri->path); print $path->basename, $/;
Re: A question on Regex
by Anonymous Monk on Mar 24, 2010 at 19:48 UTC
    use URI; sub URI::file { return (shift->path_segments)[-1] } my $mystring = "http://192.162.143.201/nightly_results/2009_12_02/log_ +lcla114.ping.com_64.html"; die URI->new( $mystring )->file; __END__ log_lcla114.ping.com_64.html at - line 5.
Re: A question on Regex
by kiruthika.bkite (Scribe) on Mar 25, 2010 at 04:02 UTC
    use strict; use warnings; my $mystring = "http://192.162.143.201/nightly_results/2009_12_02/log_ +lcla114.ping.com_64.html"; if($mystring=~/(.*)\/(.*)/) { print "File Name : $2"; }

    Output
    File Name : log_lcla114.ping.com_64.html