4

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

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a look-ahead assertion to require that mazda is followed by a number without actually matching it:

str = "mazda mazda6 mazda 6 mazda3 mazda2"
re.sub(r'mazda(?=\d+)', r'', str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.