Match filename and file extension from single Regex
Assuming that all files do have an extension, you could use
var regexAll = /[^\\]*\.(\w+)$/;
Then you can do
var total = path.match(regexAll);
var filename = total[0];
var extension = total[1];
I know this is an old question, but here's another solution that can handle multiple dots in the name and also when there's no extension at all (or an extension of just '.'):/^(.*?)(\.[^.]*)?$/
Taking it a piece at a time:^
Anchor to the start of the string (to avoid partial matches)
(.*?)
Match any character .
, 0 or more times *
, lazily ?
(don't just grab them all if the later optional extension can match), and put them in the first capture group (
)
.
(\.
Start a 2nd capture group for the extension using (
. This group starts with the literal .
character (which we escape with \
so that .
isn't interpreted as "match any character").
[^.]*
Define a character set []
. Match characters not in the set by specifying this is an inverted character set ^
. Match 0 or more non-.
chars to get the rest of the file extension *
. We specify it this way so that it doesn't match early on filenames like foo.bar.baz
, incorrectly giving an extension with more than one dot in it of .bar.baz
instead of just .baz
.
.
doesn't need escaped inside []
, since everything (except^
) is a literal in a character set.
)?
End the 2nd capture group )
and indicate that the whole group is optional ?
, since it may not have an extension.
$
Anchor to the end of the string (again, to avoid partial matches)
If you're using ES6 you can even use destructing to grab the results in 1 line:[,filename, extension] = /^(.*?)(\.[^.]*)?$/.exec('foo.bar.baz');
which gives the filename as 'foo.bar'
and the extension as '.baz'
.'foo'
gives 'foo' and ''
'foo.'
gives 'foo'
and '.'
'.js'
gives ''
and '.js'
You can use groups in your regular expression for this:
var regex = /^([^\\]*)\.(\w+)$/;
var matches = filename.match(regex);
if (matches) {
var filename = matches[1];
var extension = matches[2];
}
/^.*\/(.*)\.?(.*)$/g
after this first group is your file name and second group is extention.
var myString = "filePath/long/path/myfile.even.with.dotes.TXT";
var myRegexp = /^.*\/(.*)\.(.*)$/g;
var match = myRegexp.exec(myString);
alert(match[1]); // myfile.even.with.dotes
alert(match[2]); // TXT
This works even if your filename contains more then one dotes or doesn't contain dots at all (has no extention).
EDIT:
This is for linux, for windows use this /^.*\\(.*)\.?(.*)$/g
(in linux directory separator is /
in windows is \
)