Regex to select a file extension

China☆狼群 提交于 2021-02-05 11:31:28

问题


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?


回答1:


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



回答2:


import re
x="MyApp.apk"
print re.sub(r"\..*$","",x)



回答3:


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



回答4:


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

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

print filename



回答5:


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'



回答6:


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')


来源:https://stackoverflow.com/questions/27151189/regex-to-select-a-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!