如果你知道文件名格式都不會改變,你不需要re
:
filename = 'myfile-20101019.txt'
basename, extension = filename.rsplit('.', 1)
firstpart, date = basename.rsplit('-', 1)
In : firstpart, date, extension
Out: ('myfile', '20101019', 'txt')
或只是不擴展名:
firstpart, date = filename.rsplit('.', 1)[0].rsplit('-', 1)
# ['myfile', '20101019']
適用於更復雜的filenam上課太:
filename = 'more.complicated-filename-20101004.txt'
firstpart, date = filename.rsplit('.', 1)[0].rsplit('-', 1)
# ['more.complicated-filename', '20101004']
或者,只是爲了更漂亮分裂擴展:
import os
filename = 'more.complicated-filename-20101004.txt'
firstpart, date = os.path.splitext(filename)[0].rsplit('-', 1)
# ['more.complicated-filename', '20101004']
謝謝,改變。*爲非貪婪。*?這是有效的。應該已經發現了! – 2010-10-15 09:54:06