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

A solution without alternation and without assertions:
s { \A /* ( (?: [^/]+ /+ )*? [^/]* ) /* \z } { length $1 ? "/$1/" : '/' }ex;
I got lazy and copped out with the /e for that edge case.. :)

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: Regex - one and only one / at beginning and end of file path
by CombatSquirrel (Hermit) on Dec 15, 2003 at 07:21 UTC
    Just TIMTOWTDI:
    unless ('/' eq substr($directory, 0, 1) and '/' eq substr($directory, -1, 1)) { ...
    I don't know how fast it is, but I generally prefer substr over RegExes in fixed-width-fixed-content problems.
    Cheers,
    CombatSquirrel.
    Entropy is the tendency of everything going to hell.

      What concern does that snippet address? I don't see how it has anything to do with anything posted anywhere on this thread?

      As for performance, despite appearances, you're actually going to have a hard time beating the regex engine. With substr, you usually have to do a (relative) lot of explicit work in Perl code, which means many more ops to interpret; with regexen, most of the infrastructure is implicit in the guts of Perl, which execute much faster.

      Makeshifts last the longest.

        It concerns checking whether or not a string starts and ends with "/", which was, as far as I can see the OPs question. I do realize that (s)he asked for a RegEx solution, but the "Is the one line solution faster than the two line solution?" part made me think that it was not really relevant in which way checking should occur. I would have assumed that substr was faster than RegExes, because it would just be a simple comparision of an array element (in C -- as I said, I didn't benchmark it, so I am making analogous assumptions) vs. something that hardly could be easier in case of the RegEx. If you say that the RegEx would probably be faster I'll have to believe you, but I don't think that my original reply could really have hurt anyone reading it.
        Just my own opinion, though.
        CombatSquirrel.
        Entropy is the tendency of everything going to hell.