简体   繁体   中英

Python regex replace with return match

Given the following string

p='12.04.2020 - 17:00 - 13.04.2020 10:00'

How do I replace the first dash (-), which is a mistake, with an empty space?

I tried with

re.sub("(20\d*) - (\d*):","\1 \2:",p)

'12.04.\x01 \x02:00 - 13.04.2020 10:00'

but it doesn't return the matches.

Edit: there may be multiple such patterns and there may not be a dash in that position, so it has to be specific, I cannot just replace the first found dash.

You need to use r modifier to prevent escaping \d to d and \1 to 1

re.sub(r"(20\d*) - (\d*):",r"\1 \2:",p)

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