Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to remove a file's extension

I am in need of a regular expression that can remove the extension of a filename, returning only the name of the file.

Here are some examples of inputs and outputs:

myfile.png     -> myfile myfile.png.jpg -> myfile.png 

I can obviously do this manually (ie removing everything from the last dot) but I'm sure that there is a regular expression that can do this by itself.

Just for the record, I am doing this in JavaScript

like image 982
Andreas Grech Avatar asked Nov 30 '09 07:11

Andreas Grech


People also ask

How do I remove a directory extension?

Open File Explorer and click View tab, Options. In Folder Options dialog, move to View tab, untick Hide extensions for known file types option, OK. Then you will se file's extension after its name, remove it.

How do I strip a filename extension in Python?

To remove the extension from a filename using Python, the easiest way is with the os module path. basename() and path. splitext() functions. You can also use the pathlib module and Path and then access the attribute 'stem' to remove the extension from a filename.


1 Answers

Just for completeness: How could this be achieved without Regular Expressions?

var input = 'myfile.png'; var output = input.substr(0, input.lastIndexOf('.')) || input; 

The || input takes care of the case, where lastIndexOf() provides a -1. You see, it's still a one-liner.

like image 131
Boldewyn Avatar answered Sep 24 '22 21:09

Boldewyn