Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: match sequences of words based on number of characters

by Kenosis (Priest)
on Feb 18, 2013 at 01:31 UTC ( #1019257=note: print w/replies, xml ) Need Help??

in reply to match sequences of words based on number of characters

As another option, here's a subroutine to which you send a string and a list of lengths. Matches are returned as an array of arrays (AoA), and the array's empty if nothing's matched:

use strict; use warnings; my $str = 'xxxx yy zzzzz xxxx qqq xxxx vv zzzzz wwww ppp'; my @lengths = qw/2 4 3/; my @seqs = getSequences( $str, @lengths ); print "@$_\n" for @seqs; sub getSequences { my ( $string, @lengths ) = @_; my ( $i, @sequences ) = 0; my $re = join '\b.+?\b', map { $i++; "(?<C$i>[a-z]{$_})" } @length +s; push @sequences, [ map $+{"C$_"}, 1 .. @lengths ] while $string =~ /\b$re\b/ig; return @sequences; }


yy xxxx qqq vv wwww ppp

You mentioned only letters, so [a-z] was used in the regex. However, you may use \\w instead, if that works better for you. Of course, sending the subroutine different lists of lengths produces different results, as the regex is dynamically built.

Replies are listed 'Best First'.
Re^2: match sequences of words based on number of characters
by nicemank (Novice) on Feb 18, 2013 at 09:43 UTC
    And Kenosis's code also works (unajacent words if needed, any combination of characters). thanks to you,


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019257]
[GotToBTru]: Several Species of Small Furry Animals Gathered Together in a Cave and Grooving with a .. Copt? No, that can't be right

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2017-04-24 21:11 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (447 votes). Check out past polls.