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 has one extension. But if it is
adfadsfads.blah.txt I just want
adfadsfads.blah. How can I do this with regex?
In regards to David’s question, ‘why would you use regex’ for this, the answer is, ‘for fun.’ In fact, the code I’m using is simple
length_of_ext = File.extname(filename).length filename = filename[0,(filename.length-length_of_ext)]
but I like to learn regex whenever possible because it always comes up at Geek cocktail parties.
- Capture filenames that start with a dot (e.g.
.logsis a file named
.logs, not a file extension), which is common in Unix.
- Gets everything but the last dot:
- Handles files with no dot:
Note: as commenter j_random_hacker suggested, this performs as advertised, but you might want to precede things with an anchor for readability purposes.
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:
how about 2 captures one for the end and one for the filename.
- Gets the Path without the last
- The file without extension
- The the extension with a
Does not support multiple
. in file name
. in file path
I realize this question is a bit outdated, however, I had some trouble finding a good source and wound up making the regex myself. To save whoever may find this time,
If you’re looking for a ~standalone~ regex
This will match the extension without the dot
This will always match the file name if it has an extention
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.
I used this pattern for simple search:
for this text:
file.ext fileext file.ext.ext file.ext fileext
fileext in the second and last lines.
I applied it in a text tree view of a folder (with spaces as indents).
Just the name of the file, without path and suffix.
Captures just the filename of any kind within an entire filepath. Purposefully excludes the file path and the file extension
- Doesn’t capture (C:Logtestbin)
- Captures (fee105d1-5008-410c-be39-883e5e40a33d)
- Doesn’t capture (.pdf)