in reply to Extracting file name from path

That said.. always try to avoid the dot star in your regexes, because they are greedy.. but if you have to use them.. u can minimize it by the ? like that: /^.*?\\(\w+\.w{3})$/


He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

Chady | http://chady.net/

Replies are listed 'Best First'.
Re: Re: Extracting file name from path
by dimmesdale (Friar) on Jun 15, 2001 at 04:18 UTC
    Actually, a dot star can be quite useful, and is considerably faster than using the non-greedy version. In this example, using dot star makes it easy, e.g.,
    /^.*\\(.*)/
    That will extract all the information after the last \. Using the .*? version it would have to be:
    /.*?\\(?!.*\\)$/
    This would aslo make it a lot slower.

    However, trying to find the last \, like in this example, could probably be made simpler by a call to reverse. Though, in the example of extracting a filename, definately you should use a module like File::Basename, as aforementioned. This way it will be portable accross systems, and it is tested for errors, so it will save you valuable time trying to fix a regex that has something wrong with it(and errors always slip in, as do special cases).

      Good advice dimmesdale, same with all the rest. But one point:

      However, trying to find the last \, like in this example, could probably be made simpler by a call to reverse

      Close, but why not rindex. Take this example:

      $file = substr($path, 1 + rindex($path,'\\'));
      It finds the last \ in the string and asigns everything after that.

      That said, I would definately use something like File::Basename if you plan on using this script more than once.

      The 15 year old, freshman programmer,
      Stephen Rawls