Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use re.sub to match and substitute any numbers after – extension?

I want to substitute from ‘datasets/4/image-3.jpg’ to ‘datasets/4/image-1.jpg’. Are there any ways to do it by using re.sub? Or should I try something else like .split("/")[-1]? I had tried below but end up getting ‘datasets/1/image-1.jpg’, but I want to keep the /4/ instead of /1/.

My Code

import re
employee_name = 'datasets/4/image-3.jpg'
label = re.sub('[0-9]', "1", employee_name)
print(label)

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

datasets/1/image-1.jpg

Expected Input

datasets/4/image-3.jpg

Expected Output

datasets/4/image-1.jpg

>Solution :

You can use

re.sub(r'-\d+\.jpg', '-1.jpg', text)

Note: If the match is always at the end of string, append the $ anchor at the end of the regex. If there can be other text after and you need to make sure there are no word chars after jpg, add a word boundary, \b. If you want to match other extensions, use a group, e.g. (?:jpe?g|png).

Regex details

  • -\d+ – one or more digits
  • \.jpg.jpg string.

See the regex demo (code generator link).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading