Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

How regex works here?

by nagalenoj (Friar)
on Apr 08, 2009 at 04:54 UTC ( #756228=perlquestion: print w/replies, xml ) Need Help??
nagalenoj has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I have to take the first 2 columns out from a line(using regular expression). For that I have written a code like follows,

use strict; use warnings; $lines = 'B6y green $1$Byf3501d$dPtaW2vCbq63sdsw'; $lines =~ s/^(\S+\s\S+)/$1/; print "$lines";

But, its matching the whole line. why?

When I have changed the regex as follows, its working fine. How both differs. Why the first one doesn't work?

$lines =~ s/^(\S+\s\S+).*/$1/;

Replies are listed 'Best First'.
Re: How regex works here?
by lakshmananindia (Chaplain) on Apr 08, 2009 at 05:27 UTC

    In the first regex you are matching only the "B6y green" and you are replacing that again with "B6y green". So the $lines is same as it is

    In the second regex you are matching "B6y green" and the remaining string and you are replacing that with "B6y green". So the $lines has only the matched pattern.

    --Lakshmanan G.

    The great pleasure in my life is doing what people say you cannot do.

      yeeeah..! Fine.. I understood.,

      So the problem is not with the matching and with the substitution.


        There's no need at all to change the original string to extract the data you want. All you need is to match it.

        if($line =~ /^(\S+\s+\S+)/) { $match = $1; }
        or even simpler:
        ($match) = $line =~ /^(\S+\s+\S+)/;
        Note that for the latter, the assignment must be in list context, not scalar context; that's what the parens around the variable on the left hand side are for.
Re: How regex works here?
by codeacrobat (Chaplain) on Apr 08, 2009 at 06:36 UTC
    have a look :-)
    use strict; use warnings; use re qw(debugcolor); my $lines = 'B6y green $1$Byf3501d$dPtaW2vCbq63sdsw'; $lines =~ s/^(\S+\s\S+)/$1/; print "$lines";

Re: How regex works here?
by AnomalousMonk (Chancellor) on Apr 08, 2009 at 07:11 UTC
    In contrast, consider matching and deleting only that which you wish to eliminate from the string:
    >perl -wMstrict -le "my $line = 'B6y green $1$Byf3501d$dPtaW2vCbq63sdsw'; $line =~ s{ \s \S+ $ }{}xms; print qq{'$line'}; " 'B6y green'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://756228]
Approved by lakshmananindia
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-02-21 00:22 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (274 votes). Check out past polls.