Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace character between two digits using re in Python?

Tags:

python

regex

I want to work on a string dataset and replace '-' with a '.' I have this dataset:

AUDI XXX-R 2-0TS
AUDI XXX-R 2-0T
AUDI X-R 2-0

I want the '-' to be replaced by '.' so all occurrences with number-number** should be replaced by number.number**

I have tried adding the following regex pattern but it replaces the Alphabet's '-' as-well

[^a-z-A-Z]?(\d)-(\d)?[a-zA-Z]?[a-z-A-Z]

I need the pattern where no matter what the string is the '-' between two digits should be replaced with '.'

like image 917
Saif Ali Avatar asked Apr 08 '26 21:04

Saif Ali


1 Answers

We can use lookaround constructs [regular-expressions.info] for this:

from re import compile as recompile

rgx = recompile(r'(?<=\d)[-](?=\d)')

for this rgx, we can then substitute like:

>>> rgx.sub('.', 'AUDI XXX-R 2-0TS AUDI XXX-R 2-0T AUDI X-R 2-0')
'AUDI XXX-R 2.0TS AUDI XXX-R 2.0T AUDI X-R 2.0'

If the digit on the right is optional, we can just omit it, like:

rgx = recompile(r'(?<=\d)[-]')

This will thus replace 3-A with 3.A as well.

like image 93
Willem Van Onsem Avatar answered Apr 10 '26 09:04

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!