Regex to select a file extension

4.3k views Asked by At

I have an apk file say MyApp.apk. I was trying to strip the .apk extension using the strip function in python. But the problem is, If my applications name is WhatsApp.apk then the function strips the letters pp also and outputs WhatsA. What Regex should I use to strip exactly the .apk away?

6

There are 6 answers

3
Leon On BEST ANSWER

Why use regex? If you only want the filename then this code will do

filename = 'MyApp.apk'
filename = filename.rsplit('.', 1)[0]

print filename

output:

MyApp
0
Alexander On

For filenames i suggest using os.path.splitext

filename = "test.txt"
os.path.splitext(filename)
# ('test', '.txt')

If you are using filename.split() as other answers suggest you may get in trouble :

filename = "this.is.a.file.txt"
filename.split(".")
#['this', 'is', 'a', 'file', 'txt']
os.path.splitext(filename)
#('this.is.a.file', '.txt')
0
cjbayesian On

To handle filenames with .s in them, you can do:

filename = 'My.App.apk'
filename = '.'.join(filename.split('.')[:-1])

print filename
1
Anonymous Platypus On

Thank you all for the lightning response. I found another solution too.

>>> import os
>>> fileName, fileExtension = os.path.splitext('/path/to/MyApp.apk')
>>> fileName
'/path/to/MyApp'
>>> fileExtension
'.apk'
0
nu11p01n73R On

You can also accomplish this if you are certain that all the files end with .apk without using the string.replace function as

>>> str.replace('.apk','')
'MyApp'

A solution using re.sub would be like

>>> import re
>>> str="MyApp.apk"
>>> re.sub('r[\.[^.]+$','',str)
'MyApp.apk'
  • \.[^.]+ matches a . followed by anything other than . till end of string
0
vks On
import re
x="MyApp.apk"
print re.sub(r"\..*$","",x)