Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex search and replace pattern with modified pattern - Python

Tags:

python

regex

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
like image 421
Testy8 Avatar asked Oct 21 '25 06:10

Testy8


1 Answers

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

like image 170
anubhava Avatar answered Oct 23 '25 19:10

anubhava



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!