in reply to Regex - one and only one / at beginning and end of file path

Unlike what cchampion is saying, you can do it in one regex, and even without using alternation and /g. A short benchmark even suggest it to be slightly faster than using two regexes. The regex:
s!^/*(.*[^/])/*$!/$1/!;
The benchmark:
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /timethese cmpthese/; chomp (our @lines = <DATA>); our (@r1, @r2, @r3); cmpthese -10 => { mikedshelton => '@r1 = map {local $_ = $_; s!^/*!/!; s!/*$!/!; $_} @lines', cchampion => '@r2 = map {local $_ = $_; s{ (?: ^ /* | (?<=[^/])/* $ ) }</>xg +; $_} @lines', abigail => '@r3 = map {local $_ = $_; s!^/*(.*[^/])/*$!/$1/!; $_} @lines', }; die "Unequal\n" unless "@r1" eq "@r2" && "@r2" eq "@r3"; __END__ /foo/bar/baz/ foo/bar/baz/ /foo/bar/baz foo/bar/baz / foo/bar foo
And the results:
Rate cchampion mikedshelton abigail cchampion 8069/s -- -20% -27% mikedshelton 10038/s 24% -- -9% abigail 11057/s 37% 10% --

Abigail

Replies are listed 'Best First'.
Re: Re: Regex - one and only one / at beginning and end of file path
by tachyon (Chancellor) on Dec 15, 2003 at 00:06 UTC

    Misread the question

      Didn't we lose the action of adding '/' when not present at the ends somewhere?   It seems that s!/{2,}!/!g; at least leaves 'foo/bar' as itself.   Which of these RE's are for explication only?
Re^2: Regex - one and only one / at beginning and end of file path
by Aristotle (Chancellor) on Dec 15, 2003 at 04:14 UTC
    ^/*(.*[^/])/*$
    That will only match if the path ends in a slash. Duh! I think I checked my brain at the door. Sigh..

    Makeshifts last the longest.

      $ perl -wle '"foo/bar" =~ m!^/*(.*[^/])/*$! and print "Aristotle i +s wrong."' Aristotle is wrong.

      Abigail