Q:

Matching consecutive characters from a string using regex

I'm not sure how to title this question, so moving along...
I'd like to be able to match a portion of a string that is a subset of a larger string. For example:

MatchPartOfThisString -> Reference string
fThisDiff -> string I'd like to be able to say matches 5 consecutive characters in

I suppose I could loop through the first string, taking the minimum number of consecutive matches from the reference string, and see if the other string matches each of the matches I get from systematically trying to match:
if(fThisDiff =~ /Match/) {
    do something...;
}
if(fThisDiff =~ /atchP/) {
    do something...;
}
if(fThisDiff =~ /tchPa/) {
    do something...;
}

etc.
I'd like to do this more elegantly though, if there is a way to interpret portions of the reference string repeatedly with a singular regex. I do not think this is the case, but I'd like confirmation regardless.

A:

Here is a basic take on it, by hand with builtin tools. 
Build a regex pattern with alternation of substrings of desired length from your reference string.
use warnings;
use strict;
use feature 'say';

sub get_alt_re {
    my ($str, $len) = @_; 
    $len //= 1;            #/
    my @substrings;
    foreach my $beg (0 .. length($str)-$len) {
        push @substrings, substr($str, $beg, $len);
    }
    return '(' .  join('|', map quotemeta, @substrings) . ')';
}   

my $ref    = q(MatchPartOfThisString);
my $target = q(fThisDiff);

my $re = get_alt_re($ref, 5);

my @m = $target =~ /$re/g;
say for @m; 

Prints the line fThis.
The code should be made more robust and general. Then, it is fairly easily modified to match for a range of lengths (not only one, 5 above). Further, it can use libraries for subtasks (those repeated calls to substr beg for C code).  But this demonstrates that a basic solution can be rather simple.

A:

There's no simple way to do this with regex features, but a couple CPAN modules can help construct such a regex in this case.
use strict;
use warnings;
use String::Substrings 'substrings';
use Data::Munge 'list2re';

my $match_string = 'MatchPartOfThisString';
my $re = list2re substrings $match_string, 5;
my $subject = 'fThisDiff';
if ($subject =~ m/($re)/) {
  print "Matched $1 from $match_string in $subject\n";
}

A:

The best approach would be to use the longest common substring algorithm (not to be confused with the similarly-named longest common subsequence algorithm) then check its length.
use String::LCSS_XS qw( lcss );

my $longest = lcss("MatchPartOfThisString", "fThisDiff");
say length($longest);

If you have really long strings and you want to to squeeze out every millisecond, a tailored version of the algorithm that quits as soon as the target length is found and that avoids building the string would be faster.

