Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Longest possible run of a single character

by Zaxo (Archbishop)
on May 22, 2006 at 21:26 UTC ( #551041=note: print w/replies, xml ) Need Help??

in reply to Longest possible run of a single character

It's simpler than that, just use regex greediness. You were very close.

my $re = qr/((.)\2+)/;
Here's an example,
$ perl -e'my $re = qr/((.)\2+)/; $_="aabccccdddeffff"; while (m/$re/g) + { printf "\"%s\" x %d\n", $2, length($1) }' "a" x 2 "c" x 4 "d" x 3 "f" x 4 $
That skips capturing lone characters as a sequence of one - change the '+' quantifier to '*' to get them, too. There is no practical limit on the length of the match.

I didn't address picking out the maximum length substring captured. There are lots of ways to do that.

Update: Ok, here's an easy way to get the max length as the search is done, using the (?{}) construct.

use re 'eval'; my $re = qr/((.)\2+)/; my ($maxlen, $maxchr, $maxloc); $_="aabccccdddeffff"; 1 while m/$re(?{ $maxlen = length($^N), $maxchr = substr($^N,0,1), $maxloc = pos() - $maxlen if length($^N) > $maxlen; })/g; print $maxchr, ' x ', $maxlen, ' at ', $maxloc, $/; __END__ c x 4 at 3
Access to the original matching chunk of the string is given by substr($_, $maxloc, $maxlen).

After Compline,

Replies are listed 'Best First'.
Re^2: Longest possible run of a single character
by ioannis (Prior) on May 23, 2006 at 09:06 UTC
    A slight improvement. It is better to set the pattern to $re = qr/((.)(?:\2)*)/ . This will allow matching strings with single chars, strings like $_ = 'abc' .
Re^2: Longest possible run of a single character
by srdst13 (Pilgrim) on May 22, 2006 at 21:38 UTC
    PERFECT! I knew there was a better mousetrap!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://551041]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2017-03-26 09:15 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (313 votes). Check out past polls.