Is it possible to find a string using regex pattern matching, manipulate it & return it?
For example:
mazda mazda6 mazda 6 mazda3 mazda2
I want 'mazda6','mazda3','mazda2' to be replaced by '6','3','2'. I can find them easily enough using regex (mazda\d), however I don't know how to replace them with a modified version of the matched pattern (i.e. the \d should remain).
Ideal output:
mazda 6 mazda 6 3 2
You can capture the number in regex and use it's back-reference in replacement:
str = "mazda mazda6 mazda 6 mazda3 mazda2"
result = re.sub(r'\bmazda(\d+)', r'\1', str)
Output:
>>> print result
'mazda 6 mazda 6 3 2'
RegEx Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With