First of all, i will find the longest matching sequences possibile, which are in the following string xx, abc and ecd.
(I use the zero-width lookahead to avoid to reset pos)
Then I'll break those substrings in parts, if abc is repeated i suspect also bc is repeated, isn't it?
Then I'll count the repetitions of only those substrings:
$s = 'xxaabcdabcabcecdecdxx';
$min_len = 2;
$min_rep = 2;
while($s=~/(.{$min_len,})(?=.*?\1)/g)
{
for my $x (0..length $1) {
@saw{ map {substr $1, $x, $_} $x+2..length $1 } = ();
}
pos($s) = pos($s) +1 -length $1; # fix
}
for (keys %saw)
{
my $saw{$_} =()= $s=~/\Q$_/g;
delete $saw{$_} if $saw{$_}<$min_rep;
}
____
a 4
ab 3
abc 3
bc 3
c 5
cd 3
d 3
e 2
ec 2
ecd 2
x 4
xx 2
The first loop find the repetitions, the second count them. if you want to get only 2 or more char substring, change $x+1 to $x+2.
Oha
Update: added regex quoting to the last re
Update: shorter and print in order of findings:
while($s=~/(\w\w+)(?=.*?\1)/g)
{
foreach $x (0..length $1) {
map {
$y = substr $1, $x, $_;
$saw{$y}++ || do {
local pos $s = 0;
my $c=()= $s=~/\Q$y/g;
print "$y => $c\n";
}
} ($x+1..length $1)
}
pos($s) = pos($s) +1 -length $1; # fix
}
Update: fix a bug in the above code, added a pos() relocation (see #fix)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.