LawnBoy
MIS
- Mar 12, 2003
- 2,881
I'm trying to extract a file extension (.any) and populate a scalar with it. I've got 4 possible situations and I can't come up with a regex that matches in all situations.
I've got:
1 - somefile.txt
2 - some.file.txt
3 - somefile..text (don't ask, my users will type in anything for a filename)
4 - somefile
After browsing this and other forums, I came up with (filename is in $_)
This works great for situations 1, 2, and 3, but in situation 4 I end up with $name = null and $ext="somefile". What I did was to throw in an extra check:
This works well enough, but it's ugly code.
How can I meet all requirements with a single regex?
I've got:
1 - somefile.txt
2 - some.file.txt
3 - somefile..text (don't ask, my users will type in anything for a filename)
4 - somefile
After browsing this and other forums, I came up with (filename is in $_)
Code:
($name, $ext) = (/^(.*?)\.?([^\.]*)$/);
Code:
($name, $ext) = (/^(.*?)\.?([^\.]*)$/);
if ($name eq '') {
$ext = '';
}
How can I meet all requirements with a single regex?