Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

Output:

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.


Comment on Re: match sequences of words based on number of characters
Select or Download Code
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,

    nicemank.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2014-09-17 21:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (99 votes), past polls