简体   繁体   中英

Regex search and replace pattern with modified pattern - Python

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 (ie 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM