Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
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
Replies are listed 'Best First'.
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' .
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?
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 chanting in the Monastery: (5)
As of 2015-07-30 04:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (270 votes), past polls