How to replace only part of the match with python re.sub

Posted by Arty on Stack Overflow See other posts from Stack Overflow or by Arty
Published on 2010-05-04T08:12:28Z Indexed on 2010/05/04 8:18 UTC
Read the original article Hit count: 227

Filed under:
|

I need to match two cases by one reg expression and do replacement

'long.file.name.jpg' -> 'long.file.name_suff.jpg'

'long.file.name_a.jpg' -> 'long.file.name_suff.jpg'

I'm trying to do the following

re.sub('(\_a)?\.[^\.]*$' , '_suff.',"long.file.name.jpg")

But this is cut the extension '.jpg' and I'm getting

long.file.name_suff. instead of long.file.name_suff.jpg I understand that this is because of [^.]*$ part, but I can't exclude it, because I have to find last occurance of '_a' to replace or last '.'

Is there a way to replace only part of the match?

© Stack Overflow or respective owner

Related posts about python

Related posts about regex