Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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/;

Comment on How regex works here?
Select or Download Code
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.

      Thanks..!
        Yes.

        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";

    print+qq(\L@{[ref\&@]}@{['@'x7^'!#2/"!4']});
Re: How regex works here?
by AnomalousMonk (Monsignor) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (17)
As of 2014-08-20 14:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (116 votes), past polls