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

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]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2018-06-22 02:26 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (120 votes). Check out past polls.