I use the following regex:
([^\\/]+?)(?:\.[^\.\\/]*)?$
Working from the end of line $ , is there an optional group that cannot be captured for a possible extension (?:\.[^\.\\/]*)? preceded by an unwanted capture group for anything but directory separators \/ . The file name group is inanimate, allowing the next group that does not contain a capture to abandon a possible extension.
The implementation will refer to the first and only capture group [1] :
var name = __filename.match(/([^\\/]+?)(?:\.[^\.\\/]*)?$/)[1];
Group capturing a file name with an inanimate / lazy specifier
([^\\/]+?) ^ lazy
An optional extension group that should be discarded bound $ to the end of the line
(?:\.[^\.\\/]*)?$ ^^ ^ non-capture optional
var regex = /([^\\/]+?)(?:\.[^\.\\/]*)?$/; [ ["abc.js", "abc"], ["/tmp/test/../lib/stuff.js", "stuff"], ["c:\\temp\\test\\..\\lib\\stuff.js", "stuff"], ["./abc/def.js", "def"], [".\\abc\\win.js", "win"], ["./lib/my-module.js", "my-module"], [".\\lib/my-dotless", "my-dotless"], ["..///lib/..\\\\.//..dots&seps..", "..dots&seps."], ["trailing-dots...js", "trailing-dots.."] ].forEach( test => { var name = test[0].match(regex)[1]; var result = test[0] + " => " + test[1] + " # " + (name === test[1] ? "Passed" : "Failed"); console.log(result); });
Evaluation courtesy of https://regex101.com
bvj Aug 02 '17 at 2:50 on 2017-08-02 02:50
source share