Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Get Filename Without Extension in One Shot?

Tags:

syntax

regex

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.

like image 976
Dan Rosenstark Avatar asked Mar 09 '09 02:03

Dan Rosenstark


5 Answers

Try this:

(.+?)(\.[^.]*$|$)

This will:

  • Capture filenames that start with a dot (e.g. .logs is a file named .logs, not a file extension), which is common in Unix.
  • Gets everything but the last dot: foo.bar.jpeg gets you foo.bar.
  • Handles files with no dot: 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.

like image 138
John Feminella Avatar answered Oct 03 '22 15:10

John Feminella


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:

(.+?)(\.[^\.]+$|$)
like image 34
Rex M Avatar answered Oct 03 '22 14:10

Rex M


how about 2 captures one for the end and one for the filename.

eg.

(.+?)(?:\.[^\.]*$|$)
like image 36
sfossen Avatar answered Oct 03 '22 16:10

sfossen


^(.*)\\(.*)(\..*)$
  1. Gets the Path without the last \
  2. The file without extension
  3. The the extension with a .

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

like image 31
user2120014 Avatar answered Oct 03 '22 15:10

user2120014


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

\w+(?![\.\w])

This will always match the file name if it has an extention

[\w\. ]+(?=[\.])

like image 1
DarmaniLink Avatar answered Oct 03 '22 15:10

DarmaniLink