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

Hi,
I have a string which looks something like this -
begin=in+the+begining&str=Greed+Suffering&end=The+End+Part<br>

I want to match the part after str, up until the &.
in other words, I want to match Greed+Suffering
Heres my hack so far -
if($str =~ /str=[a-zA-Z]+/) { print "\nMatch: $1"; }
I thought that $1 would have been assigned "Greed", but instead I get a runtime error saying that $1 is uninitailised. What am I doing wrong?

Replies are listed 'Best First'.
Re: Regex String Matching
by sauoq (Abbot) on Sep 08, 2002 at 19:00 UTC
    . . .I get a runtime error saying that $1 is uninitailised.

    You need to use parentheses to capture the match.

    $str =~ /str=([a-zA-Z]+)/

    Since you mention you want everything up to the next '&' you might be better off with a regex that does what you mean:

    $str =~ /str=([^&]*)/
    Edit: Fixed that typo. Arien++
    -sauoq
    "My two cents aren't worth a dime.";
    
      $str =~ /str=([^&])*/;

      There's a typo in that regex, you want the star inside the parens. (You are now putting the last non-ampersand following str=, if any, into $1.)

      $str =~ /str=([^&]*)/;

      — Arien

Re: Regex String Matching
by Steve_p (Priest) on Sep 08, 2002 at 19:01 UTC
    I'm guessing that you are trying to parse parameters passed into a CGI script. If this is the case, you should not be using a Regex, but the CGI module instead and looking at the params passed in. I would suggest taking a look at Ovid's Web Programming With Perl course.