http://www.perlmonks.org?node_id=826896


in reply to Re^2: regex trouble
in thread regex trouble

Matching by itself only checks whether a string conforms to a pattern that you defined in the regular expression.

You capture strings using brackets - ( ).

If you have only one string to capture, then the way that almut suggested will work.

If you have more than one string, you have several ways to capture them:

First way:

#!/usr/bin/perl -l my $para = "xyz-xyz-xyz-xyz-v09.11-e020xyz-xyz-xyz-"; my ($part1, $part2) = $para =~ m/(v\d{2}\.\d{2})-([a-z]\d{3})/; print "$part1, $part2"; # v09.11, e020

Second way:

#!/usr/bin/perl -l my $para = "xyz-xyz-xyz-xyz-v09.11-e020xyz-xyz-xyz-"; if ($para =~ m/(v\d{2}\.\d{2})-([a-z]\d{3})/) { my ($part1, $part2) = ($1, $2); # the variables $1 and $2 are crea +ted automatically after a successful match print "$part1, $part2"; # v09.11, e020 }

Third way - very readable, but will only work in Perl 5.10:

#!/usr/bin/perl -l my $para = "xyz-xyz-xyz-xyz-v09.11-e020xyz-xyz-xyz-"; if ($para =~ m/(?<part1>v\d{2}\.\d{2})-(?<part2>[a-z]\d{3})/) { print "$+{part1}, $+{part2}"; # v09.11, e020 }

(You should probably pick better names that "part1" and "part2". I only gave them as an example.)

Replies are listed 'Best First'.
Re^4: regex trouble
by blackgoat (Acolyte) on Mar 05, 2010 at 10:32 UTC

    I have to run a command in unix. And I have to match this expression from whatever output I get. I tried doing the following:

    my $var = 'command'; my ($exp) = $var =~ m/(v\d{2}\.\d{2})-([a-z]\d{3})/;

    The same is followed by a html script in which the value of $exp must appear. But I am unable to do so...

    Can u pls help!

    Thanks

    BG

      You probably want to do something like

      my $var = `command`;

      Notice that the single quotes were replaces by backticks. There are certain problems with using backticks, but it's usually OK to use them to run a simple and safe command.

      Also, your current code will only capture v09.11. If you want to capture v09.11-e020, use this:

      my ($exp) = $var =~ m/(v\d{2}\.\d{2}-[a-z]\d{3})/;

        I'm getting the following error:

        Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE v\d{2}\.\d{2}(a-z\d{3})/