Reputation: 23
I have some kind of the file name:
Love Scene (2021) 01 TMP.mp4
Love.Scene.2021 02.TMP.mp4
Love.Scene.2021.03.TMP.mp4
LoveScene04.TMP.mp4
01, 02, 03, 04 is the episode number.
In a correct name, it should be:
Love Scene (2021) E01 TMP.mp4
Love.Scene.2021 E02.TMP.mp4
Love.Scene.2021.E03.TMP.mp4
LoveScene.E04.TMP.mp4
How to use Regular Expression to add "E" before the Episode number?
Upvotes: 2
Views: 34
Reputation: 934
Considering the data in the data.txt file, then string replace using regular expression can be done in the following way. Output will be generated in output.txt
import re
def replaceString(d, prefx='E'):
val = re.findall(r'\d{2}\b', d)
if(len(val) > 0):
d = (prefx+val[-1]).join(d.rsplit(val[-1], 1))
print(d)
return d
def handleData():
prefx="E"
file1 = open('data.txt', 'r')
file2 = open('output.txt','w+')
for line in file1.readlines():
if not line.strip():
continue
line=replaceString(line,prefx)
file2.write(line)
file1.close()
file2.close()
handleData()
input data.txt:
Love Scene (2021) 01 TMP.mp4
Love.Scene.2021 02.TMP.mp4
Love.Scene.2021.03.TMP.mp4
LoveScene04.TMP.mp4
output:
Love Scene (2021) E01 TMP.mp4
Love.Scene.2021 E02.TMP.mp4
Love.Scene.2021.E03.TMP.mp4
LoveSceneE04.TMP.mp4
Upvotes: 1