Do you remember my Unique-Character Substring post from many months ago? Well, today, ihb- and tybalt89 posed the same challenge on DALnet #perl. Except they were looking for a regex to do the trick. The shortest one. Fore!

So then they asked me, since they know of my reputation as a regex-maniac. I tried several approaches, and they were all far over par. (At first, ihb- said it was 60, but he'd dropped \Q\E somewhere, so par is 64.)

Then I was struck by the easiest solution. Match a character, and then match a dynamic character class of anything BUT what you just matched. This dynamic character class is generated via (??{ ... }).

In the end, he and I had the exact same code, developed independently -- for, while I had asked him "did you use sort?" and "did you use look-ahead?" and "did you remember /s?", his answers were all yes, and I had already crafted my answer. I found it scarily odd that we had converged on the one way to do it (insomuchas it is the most compact solution, and represents the standard algorithm used).
(sort{length$b<=>length$a}pop=~/(?=(.(??{"[^\Q$&\E]"})*))/gs)[0]


japhy -- Perl and Regex Hacker

Replies are listed 'Best First'.
Re: TOOWTDI (There's Only One Way To Do It)
by MeowChow (Vicar) on Jun 06, 2001 at 00:50 UTC
    In theory, the following should also work, but Perl doesn't like it one bit:
    (sort{length$b<=>length$a}pop=~/.*(?(?{$&=~'(.).*\1'})^)/gs)[0]
    update: blech, actually in theory it wouldn't work since i'm not using a zero-width assertion for remainder of the matched strings, but it's still interesting that it segfaults Perl.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
      Let me guess... segfault? ;) A lot of approaches I wanted to take ended up screwing up Perl, because they used a regex in a regex, and that greatly upset the engine.

      japhy -- Perl and Regex Hacker