re.sub() - Regex for replacing last occurance of a substring in a string

python, regex, string

Solution

using a greedy quantifier and a capture group:

re.sub(r'(.*)cr[^.]*', '\\1', input)

Problem

I'm trying to replace the last occurrence of a substring from a string using re.sub in Python but stuck with the regex pattern. Can someone help me to get the correct pattern? ``` String = "cr US TRUMP DE NIRO 20161008cr_x080b.wmv" ``` or `String = "crcrUS TRUMP DE NIRO 20161008cr.xml"` I want to replace the last occurrence of "`cr`" and anything before the extension. desired output strings are - ``` "cr US TRUMP DE NIRO 20161008.wmv" "crcrUS TRUMP DE NIRO 20161008.xml" ``` I'm using `re.sub` to replace it. ``` re.sub('pattern', '', String) ``` Please advise.

Original source