如何匹配出现最长的子串?

如何匹配出现最长的子串?

请各位指教一下如何做?

如有字串:
aaabaaaabaaaaabaaaaaaaabaaaaaaaaaaaabaabaaa

我想匹配出最长的那串a,如何做?我的预期是取到aaaaaaaaaaaa。谢谢了。

文不对题嘛
Do a global match with /g first
Extract from the result the longest match

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;
use warnings;
$_ = "aaabaaaabaaaaabaaaaaaaabaaaaaaaaaaaabaabaaa";
my @match = /(a+)/g;
my $max   = 0;
foreach (@match) {
    $max = $_ if ( length $_ > length $max );
}
print "Longest match is \[$max]\n";

或者用这个
参考自mastering regular expression pattern

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;
use warnings;
$_ = "aaabaaaabaaaaabaaaaaaaabaaaaaaaaaaaabaabaaa";
my $pattern = qr/a+/;
my $longest = undef;
my $recordmatch = qr/(?{if ( not defined $longest or length $& > length $longest){$longest =$&;}})(?!)/;
m/$pattern$recordmatch/;
if (defined $longest){
        print "Longest match = \[$longest]\n";
}else {
        print "No match\n";
}

谢谢
收到了。