Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text.
re.sub(r'(\_a)?\.([^\.]*)$' , r'_suff.\2',"long.file.name.jpg")
More Related Contents:
- Regular expression doesn't produce expected result
- How t extract last part of a text in python [duplicate]
- re.findall behaves weird
- Do regular expressions from the re module support word boundaries (\b)?
- Python extract pattern matches
- Split a string by spaces — preserving quoted substrings — in Python
- Does “\d” in regex mean a digit?
- Remove all special characters, punctuation and spaces from string
- Reversing a regular expression in Python
- re.findall not returning full match?
- re.sub replace with matched content
- re.sub erroring with “Expected string or bytes-like object”
- Can’t use ‘\1’ backreference to capture-group in a function call in re.sub() repr expression
- Python regex, matching pattern over multiple lines.. why isn’t this working?
- BeautifulSoup returns empty list when searching by compound class names
- What does the “r” in pythons re.compile(r’ pattern flags’) mean?
- Python regex to match dates
- regexes: How to access multiple matches of a group? [duplicate]
- Do Python regular expressions have an equivalent to Ruby’s atomic grouping?
- Finding words after keyword in python [duplicate]
- Grep and Python
- Regexp to remove specific number of occurrences of character only
- re.search() only matches the first occurrence
- How to get the first word in the string
- Python: UserWarning: This pattern has match groups. To actually get the groups, use str.extract
- Generate a String that matches a RegEx in Python [duplicate]
- Split string at commas except when in bracket environment
- Using ^ to match beginning of line in Python regex
- How to split long regular expression rules to multiple lines in Python
- Python regular expression not matching