chargrill has asked for the wisdom of the Perl Monks concerning the following question:
Hello.
I'm trying to expand my knowledge of regexen, especially more advanced uses for them, beyond simple things like matching e-mail address, for example ;)
I'm trying to find a repeated substring in a larger string. Given the following code:
#!/usr/bin/perl use strict; use warnings; my @found; # 0 1 2 3 4 5 # 012345678901234567890123456789012345678901234567890 $_ = q'abczdefzabcghijklzabczaerabrtyuabcethdauthabkudiabc'; # abc abc abc abc abc # 0 8 18 31 48 m< ( (?{ push @found, pos() }) abc # the string I know which repeats ) \G .+? \1 >gx; print join ', ', @found, "\n";
Which prints: 0, 8, 18, 31, 48, - exactly the positions I know the substring is in relative to the larger string.
But suppose I don't know ahead of time _what_ the repeating pattern is, but would still like to detect it? Leaving the rest of the code alone, I change the regex to:
m< ( (?{ push @found, pos() }) [a-z]{3} # suppose i'm looking for a series of 3 repeating char +acters... ) \G .+? \1 >gx;
This doesn't work at all as i'd hope; it prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
Can anyone help me out with at the very least a shove in the right direction? I've tried as many variations as I can think of, inserting variations of (?{ print pos(), $^N }) into various places, and just can't figure out what I need to change to achieve my desired results.
$,=42;for(34,0,-3,9,-11,11,-17,7,-5){$*.=pack'c'=>$,+=$_}for(reverse s +plit//=>$* ){$%++?$ %%2?push@C,$_,$":push@c,$_,$":(push@C,$_,$")&&push@c,$"}$C[$# +C]=$/;($#C >$#c)?($ c=\@C)&&($ C=\@c):($ c=\@c)&&($C=\@C);$%=$|;for(@$c){print$_^ +$$C[$%++]}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Finding a repeating substring with a regex
by davido (Cardinal) on Apr 15, 2006 at 08:45 UTC | |
|
Re: Finding a repeating substring with a regex
by japhy (Canon) on Apr 15, 2006 at 13:03 UTC | |
|
Re: Finding a repeating substring with a regex
by kvale (Monsignor) on Apr 15, 2006 at 08:29 UTC | |
|
Re: Finding a repeating substring with a regex
by TedPride (Priest) on Apr 16, 2006 at 00:56 UTC |