I want to get just the filename using regex, so I\'ve been trying simple things like
([^\\.]*)
which of course work only if the filename ha
Just the name of the file, without path and suffix.
^.*[\\|\/](.+?)\.[^\.]+$
Everything followed by a dot followed by one or more characters that's not a dot, followed by the end-of-string:
(.+?)\.[^\.]+$
The everything-before-the-last-dot is grouped for easy retrieval.
If you aren't 100% sure every file will have an extension, try:
(.+?)(\.[^\.]+$|$)
^(.*)\\(.*)(\..*)$
\
.
Examples:
c:\1\2\3\Books.accdb
(c:\1\2\3)(Books)(.accdb)
Does not support multiple .
in file name
Does support .
in file path
I used this pattern for simple search:
^\s*[^\.\W]+$
for this text:
file.ext
fileext
file.ext.ext
file.ext
fileext
It finds fileext
in the second and last lines.
I applied it in a text tree view of a folder (with spaces as indents).
Try this:
(.+?)(\.[^.]*$|$)
This will:
.logs
is a file named .logs
, not a file extension), which is common in Unix.foo.bar.jpeg
gets you foo.bar
.secret-letter
gets you secret-letter
.Note: as commenter j_random_hacker suggested, this performs as advertised, but you might want to precede things with an anchor for readability purposes.
Ok, I am not sure why I would use regular expression for this. If I know for example that the string is a full filepath, then I would use another API to get the file name. Regular expressions are very powerfull but at the same time quite complex (you have just proved that by asking how to create such a simple regex). Somebody said: you had a problem that you decided to solve it using regular expressions. Now you have two problems.
Think again. If you are on .NET platform for example, then take a look at System.IO.Path class.