Regex to match the longest repeating substring

前端 未结 5 723
予麋鹿
予麋鹿 2020-12-09 18:33

I\'m writing regular expression for checking if there is a substring, that contains at least 2 repeats of some pattern next to each other. I\'m matching the result of regex

5条回答
  •  既然无缘
    2020-12-09 18:46

    Here's a long-ish script that does what you ask. It basically goes through your input string, shortens it by one, then goes through it again. Once all possible matches are found, it returns one of the longest. It is possible to tweak it so that all the longest matches are returned, instead of just one, but I'll leave that to you.

    It's pretty rudimentary code, but hopefully you'll get the gist of it.

    use v5.10;
    use strict;
    use warnings;
    
    while () {
        chomp;
        print "$_ : ";
        my $longest = foo($_);
        if ($longest) {
            say $longest;
        } else {
            say "No matches found";
        }
    }
    
    sub foo {
        my $num = shift;
        my @hits;
        for my $i (0 .. length($num)) {
            my $part = substr $num, $i;
            push @hits, $part =~ /(.+)(?=\1)/g;
        }
        my $long = shift @hits;
        for (@hits) {
            if (length($long) < length) {
                $long = $_;
            }
        }
        return $long;
    }
    
    __DATA__
    56712453289
    22010110100
    5555555
    1919191919
    191919191919
    2323191919191919
    

提交回复
热议问题