Reputation: 1607
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
Upvotes: 2
Views: 3597
Reputation: 163277
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+
For example:
re.sub(r'(?<=FR)\d+','',t)
Upvotes: 1
Reputation: 626747
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.
Upvotes: 3