LPM: RegEx quiz!

Rich Bowen rbowen at rcbowen.com
Sat Mar 11 19:58:51 CST 2000


David Hempy wrote:
> 
> Okay, all you macho RegEx wizards...
> 
> I want to turn a file path into a URL.  I want to allow filenames like
> "../images/logo.gif".  I will then prepend the project folder, so you get
> something like: "/www/mydepartment/myproject/../images/logo.gif".  Works
> fine for file access, but parent references ("../") do not work in
> URL's.  I need to reduce this to "/www/mydepartment/images/logo.gif".
> 
> I thought I had it licked in a single regex, but it balked when you had
> grandparent references ("../../"):
> 
>         $url =~ s|/.?/\.\.(?=/)||g;
> 
> In the end, I resorted to putting the regex in a loop...seems to work, but
> pains my ego:
> 
>         $url = "/a/b/c/u/../v/../d/e/w/../x/y/z/9/../../../../f/index.html";
>         print "Start with $url\n";
>         while ($url =~ s|/.?/\.\.(?=/)||g) {
>                 print " Then make $url\n";
>         }
>         print "  End with $url\n";
> 
> Anybody have a leaner solution?

Seems to me that this is about the best way to do it. At least, I can't
come up with a better one. If you really want to get something better,
I'd suggest asking on the Fun With Perl mailing list. I'm sure that
someone there will hvae something entertaining.

Rich
-- 
http://www.ApacheUnleashed.com/
Lexington Perl Mongers - http://lexington.pm.org/
PGP Key - http://www.rcbowen.com/pgp.txt



More information about the Lexington-pm mailing list