As bikeNomad said, you are missing a backslash before the
w for matching the extension. The following should work:
/.*\\(\w+\.\w{3})/;
Also take a look at File::Basename and File::Spec, which
have different methods for splitting and massaging paths
and filenames.
--ZZamboni
| [reply] [d/l] |
my $str = 'c:\dir\subdir\filename.ext';
my $filename = (split/\\/, $str)[-1];
Grabs everything after the last \ and I'm willing to bet much faster (and it's easier to read than that regexp). If I had retained more of the context talks in 'Camel' I seem to remeber you can drop the [-1] by getting it to still be in list context when assigned to $filename (instead of $filename getting the scalar 4) but I can't find the refference. | [reply] [d/l] |
That's not working because it's looking for three w's at the end of the name. If you don't have to validate the file name, why not just something like: m{([^\\/]+)$}
| [reply] [d/l] |
my $str = 'c:\dir\subdir/filename.ext';
my $filename = ( split /\\|\//, $str )[-1];
but then of course you have a regex in there, oh well.
tachyon | [reply] [d/l] |
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/
| [reply] [d/l] [select] |
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). | [reply] [d/l] [select] |
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 | [reply] [d/l] |