user3525290
user3525290

Reputation: 1607

python re.sub replace number in match string

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

Answers (2)

The fourth bird
The fourth bird

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+

Regex demo | Python demo

For example:

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions