Your solution is almost correct. Use this:
^.*\.[^\\]+$
Sample at rubular.
Vra
I am looking for a regex to test if a file has any extension. I define it as: file has an extension if there is no slashes present after the last ".". The slashes are always backslashes.
I started with this regex
.*\..*[^\\]
Which translates to
.* Any char, any number of repetitions
\. Literal .
.* Any char, any number of repetitions
[^\\] Any char that is NOT in a class of [single slash]
This is my test data (excluding ##, which is my comments)
\path\foo.txt ## I only want to capture this line
\pa.th\foo ## But my regex also captures this line <-- PROBLEM HERE
\path\foo ## This line is correctly filtered out
What would be a regex to do this?
Oplossing
Ander wenke
I wouldn't use a regular expression here. I'd split
on /
and .
.
var path = '\some\path\foo\bar.htm',
hasExtension = path.split('\').pop().split('.').length > 1;
if (hasExtension) console.log('Weee!');
Here goes a more simple function to check it.
const hasExtension = path => {
const lastDotIndex = path.lastIndexOf('.')
return lastDotIndex > 1 && path.length - 1 > lastDotIndex
}
if (hasExtension(path)) console.log('Sweet')
You can also try even more simpler approach:
(\.[^\\]+)$
Details:
$ = Look from the end of string
[^\\]+ = Any character except path separator one or more time
\. = looks for <dot> character before extension