简体   繁体   中英

using python re.sub, how can I maintain part of the expression and replace just a part of it not knowing the exact characters?

I want to search for occurrences of a number, space, and number in each line in a file, and replace those occurences with the same numbers, but with 2 spaces in between instead of one.

I can't just search for 1 space and replace with 2 since there may be other occurences of a single space between characters (letters) that I want to keep. I tried this:

newLine = re.sub('\d\s\d','\d\s\s\d',t2line)

but the output actually takes the replacement literally, and so I see \\d\\s\\s\\d in the newLine . Is there a way to do this?

Here is an example of a line where I would like to apply this replacement:

38 120 666377.664 1822418.378 20.373 0 0HV38 MB-194 ped.walkway of Li

Try using the regex

(?<=\d) (?=\d)

and replace with ' ' (two spaces)

see here: https://regex101.com/r/wE5pM9/3

Edit: sorry for all the edits, I forgot you wanted to sub 1 space for 2. I hope it's right this time!

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