Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Perl Regex Repeating Patterns

by Corion (Pope)
on Jan 17, 2012 at 21:21 UTC ( #948419=note: print w/replies, xml ) Need Help??


in reply to Perl Regex Repeating Patterns

Having a quantifier after capturing parentheses is almost always an error.

Maybe you want to directly populate your list?

my @matches = ($string =~ /([A-Z]{3})/g;

but that approach will not work if your input data contains non-alphabetical chars, like:

AAA..BBB

If you want a match to start at a specific position, see perlre on \G.

Replies are listed 'Best First'.
Re^2: Perl Regex Repeating Patterns
by Anonymous Monk on Jan 17, 2012 at 21:43 UTC

    Thanks for the response. The following regex worked properly. I realize that using a quantifier after a capture group is bad programming practice, but I do not know how else to do what I want

    my $string="AAABBBCCCCDDDEEEFFFGGGHHHIII"; my @patterns=('BBB','DDD'); my @index; foreach(@patterns){ while($string=~m/\G([A-Z]{3})+?$_/g){ push(@index,$-[2]); pos($string)=$-[2]; }
    If there is a better way to do this, please let me know. Thanks.
      The following regex worked properly. ... If there is a better way to do this ...

      Even after adding (just for the heck of it) a closing  } brace, all I get is an infinite loop. What code are you running?

      >perl -wMstrict -le "my $string=\"AAABBBCCCCDDDEEEFFFGGGHHHIII\"; my @patterns=('BBB','DDD'); my @index; foreach(@patterns){ while($string=~m/\G([A-Z]{3})+?$_/g){ push(@index,$-[2]); pos($string)=$-[2]; print 0+@index; <STDIN>; } } " 1 2 3 4 5 ... Terminating on signal SIGINT(2)

      Putting a repeating quantifier after a capture simply does not do what you intend it to do, unless you only want to capture the last matched item in the repetition. And even then, it would be clearer in my opinion to explicitly state your assumption, by explicitly discarding the first repetitions:

      /(?:[A-Z]{3})*([A-Z]{3})$/

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://948419]
help
Chatterbox?
[LanX]: whats the best way to restrict a MySQL Text Column to alphanums + underscore ?
[LanX]: CHARACTER SET?
[chacham]: ought to be a check constraint.
[chacham]: there's a regexp function. if that can be used ina check() constraint...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (16)
As of 2017-03-30 15:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (360 votes). Check out past polls.