Here's a possible solution for what—I think—you're trying to achieve:
#! /usr/bin/env perl
use 5.014; use warnings;
# We're going to try matching substrings of this...
my $MASTER_STR = 'abcdabcdabceabcdabcdabceab';
# Using this pattern to find (possibly truncated) repetitions...
my $REPETITION_PAT = qr{
\A # Start at the beginning of the string
(.+?) # Match minimal initial sequence (as $1)
(?{$^N}) # Remember it internally (as $^R)
(?| # Then either it's not truncated...
\1+ # Rematch it exactly as often as possible
\z # ...until the end of the string
() # Remember that nothing was left over (as $2)
| # Or else it is truncated...
\1* # Rematch it exactly as often as possible (or not)
(.+) # Then grab what's left (as $2)(internally as $^N)
\z # ...until the end of the string
# Then verify that what's left is a proper truncation...
(??{
# If what's left ($^N) is substring of repetition ($^R)...
$^N eq substr($^R,0,length($^N))
? q{} # ...then do nothing (i.e. keep matching)
: q{(?!)} # ...else initiate backtracking
})
)
}xms;
# Loop through increasingly truncated substrings...
for my $substr (1..length($MASTER_STR)) {
# Compute the substring...
my $str = substr($MASTER_STR,0,-$substr);
# Evaluate the match...
if ($str =~ $REPETITION_PAT) {
say "$str\n Matched: $1*$2";
}
else {
say "$str\n Didn't match";
}
}
Damian
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|