2

Replacing numbers in a string after the match.

t = 'String_BA22_FR22_BC'
re.sub(r'FR(\d{1,})','',t)

My desired output would be String_BA22_FR_BC

1
  • Try using a lookbehind instead to match the digits (?<=FR)\d+ Commented Dec 20, 2018 at 12:07

2 Answers 2

3

You may use

re.sub(r'FR\d+','FR',t)

Alternatively, you may capture the part you need to keep with a capturing group and replace with \1 backreference:

re.sub(r'(FR)\d+', r'\1', t)
         ^--^- >>>----^

See the Python demo

A capturing group approach is flexible as it allows patterns of unlimited length.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I've re.sub(r'(FR|ZZ)\d+', r'\1', t). This allowing me search multiple character groups.
@user3525290 Yes, you will even be able to use something like re.sub(r'((?:FR|ZZ)[a-z]*)\d+', r'\1', t) using this approach if need be.
I am guessing [a-z] is checking for upper or lower case?
@user3525290 [A-Za-z]* will match 0 or more ASCII letters. [^\W\d_]* will match any 0+ letters. [a-z]* only matches 0+ lowercase ASCII letters if re.I flag is not specified.
1

You are replacing what you match (in this case FR22) with an empty string.

Another option is to use a positive lookbehind an then match 1+ digits adn replace that match with an empty string:

(?<=FR)\d+

Regex demo | Python demo

For example:

re.sub(r'(?<=FR)\d+','',t)

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.