Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

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 (Canon) 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 scrutinizing the Monastery: (6)
As of 2017-02-28 07:11 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (397 votes). Check out past polls.