1

Say I have a string like so

txt = 'Source_Test_MyStuff_v001.0746.exr'
name = re.sub(r'\.([0-9]+)\.', '#', txt )

Outputs:

Source_Test_MyStuff_full_v001#exr

My goal is to find the group containing only numbers between the two periods .. and replace each number within the periods (.) with pound signs.

The desired result is this... Outputs:

Source_Test_MyStuff_full_v001.####.exr

Other examples that could occur:

Source_Test_MyStuff_v001.0586006.exr >> Source_Test_MyStuff_v001.#######.exr
Source_Test_MyStuff_v001.76.exr >> Source_Test_MyStuff_v001.##.exr

How can i achieve this with python and regex?

1 Answer 1

2

You can use

re.sub(r'(?<=\.)[0-9]+(?=\.)', lambda x: '#'*len(x.group()), txt )

The (?<=\.)[0-9]+(?=\.) regex match one or more digits only when they are enclosed with dot chars on both ends, and lambda x: '#'*len(x.group()) replaces the matches with the same amount of # chars as the match length.

See a full Python demo:

import re
txt = 'Source_Test_MyStuff_v001.0746.exr'
print( re.sub(r'(?<=\.)[0-9]+(?=\.)', lambda x: '#'*len(x.group()), txt ) )
# => Source_Test_MyStuff_v001.####.exr
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.