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

Hello Monks,

Please tell me what might be wrong with my regex:

My string is: $string = "hello = 1234ab;cat;dog;4892";

I want to grab everything between the 2nd the and 3rd semicolons...

my $semiColon=2; if ( $string =~ /hello.*=(\s*.*;\s*){$semiColon}(\s*.*;\s*).*/i ) my $substring = $2;
The $substring should print out dog, but instead it grabs all the string.

Thanks a lot in advance

Replies are listed 'Best First'.
Re: regex picking out a particular string
by BUU (Prior) on Feb 04, 2005 at 02:10 UTC
    Heres a better way:
    my $substring = (split( ';', $string))[2];
      Thank you all...that does help
      my $substring = (split( ';', $string))[2];

      A regular expression should look line a regular expression.

      my $substring = (split( /;/, $string))[2];
Re: regex picking out a particular string
by Roy Johnson (Monsignor) on Feb 04, 2005 at 01:59 UTC
    Works for me:
    use strict; use warnings; my $string = "hello = 1234ab;cat;dog;4892"; my $semiColon=2; if ( $string =~ /hello.*=(\s*.*;\s*){$semiColon}(\s*.*;\s*).*/i ) { my $substring = $2; print "$substring\n"; }
    I would recommend that you at least modify your dot-stars to be .*? (non-greedy). And get rid of the trailing one. That one's useless.
    /hello.*?=(\s*.*?;\s*){$semiColon}(\s*.*?;\s*)/i

    Caution: Contents may have been coded under pressure.
Re: regex picking out a particular string
by gube (Parson) on Feb 04, 2005 at 04:00 UTC

    Hi, try this in regex;

    $string = "hello = 1234ab;cat;dog;4892"; $string =~ m#([^;]*?)\;([^;]*?);([^;]*?);#gsi; print $3; o/p:Dog

    Regards,
    Gubendran.l
Re: regex picking out a particular string
by nobull (Friar) on Feb 04, 2005 at 20:17 UTC
    It has been pointed out that you should use split() but if you'd rather use match:
    my $semiColon=2; my ($substring) = $string =~ /(?:;.*?){$semiColon}(.*?);/;

    If you want to find the nth piece of a m-piece string where n << m it can make sense to use the match approach.

    Note: $substring will be undef is $string contained fewer then $semiColon+1 semicolons.

    Update: Correction, I meant where n and m are both large. If n is small then simply use the LIMIT arg of split!