Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

TOOWTDI (There's Only One Way To Do It)

by japhy (Canon)
on Jun 06, 2001 at 00:15 UTC ( [id://85994]=perlmeditation: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://85994]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-20 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found