Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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,
Zaxo


Comment on Re: Longest possible run of a single character
Select or Download Code
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!
Re^2: Longest possible run of a single character
by ioannis (Vicar) 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' .

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://551041]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (9)
As of 2014-12-29 03:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (184 votes), past polls