Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^3: regex trouble

by amir_e_a (Hermit)
on Mar 05, 2010 at 07:11 UTC ( #826896=note: print w/replies, xml ) Need Help??


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})/

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://826896]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2019-12-07 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (162 votes). Check out past polls.

    Notices?