Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Limiting number of regex matches

by Anonymous Monk
on Sep 25, 2012 at 20:27 UTC ( #995629=note: print w/ replies, xml ) Need Help??


in reply to Limiting number of regex matches

#!/usr/bin/perl -- use strict; use warnings; use Data::Dump; my $str ='dog dog dog dog dog'; my @dogs ; while( @dogs < 3 and $str =~ /(dog)/g ){ push @dogs, $1; } dd \@dogs; __END__ ["dog", "dog", "dog"]


Comment on Re: Limiting number of regex matches
Download Code
Re^2: Limiting number of regex matches
by 2teez (Priest) on Sep 25, 2012 at 21:06 UTC

    Or Maybe this:

    use warnings; use strict; my $str = 'dog dog dog dog dog'; print join " " => ( split /\s+/, $str )[ 0 .. 2 ];
    Output
    dog dog dog

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
      That doesn't limit the number of matches, it still counts/matches every single dog in the string

        Yes, why use a regex to match for an obvious substring in this case, when a string could be splited into an array, a slice of that which got the required output printed?
        Please, don't forget that the OP also asked among other things "..Is there no other way.."? Am simply showing, some other ways, in this case.

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2014-12-27 04:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls