in reply to want regex to find 2nd and 3rd occurence of a character

Using split to cut up the string but capturing the delimiters so they do not get lost.

use strict; use warnings; my $str="AJKDHAKAESRADADKLASRRASDASDKASEKA"; #split on K or R and keep the delimiters my @parts = split /([KR])/, $str; print "@parts\n\n"; # return parts in groups so each group has 2 K or R my $start = 0; foreach my $end (1 .. $#parts / 4) { print join '', @parts[$start .. ($end * 4 - 1)], "\n"; $start = $end * 4; } print "\n"; # return parts in groups so each group has 3 K or R $start = 0; foreach my $end (1 .. $#parts / 6) { print join '', @parts[$start .. ($end * 6 - 1)], "\n"; $start = $end * 6; }

Can you see the pattern emerging?

Or using a single regex:

use strict; use warnings; my $str="AJKDHAKAESRADADKLASRRASDASDKASEKA"; my @parts = $str =~ m/((?:[^KR]*[KR]){2})/g; print "@parts\n\n"; @parts = $str =~ m/((?:[^KR]*[KR]){3})/g; print "@parts\n";

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: want regex to find 2nd and 3rd occurence of a character
by heidi (Sexton) on May 22, 2008 at 19:39 UTC
    It works obsoultely fine. simple and clear thank you very much for the help.