简体   繁体   中英

python re.sub() with pair or characters

I am trying to grab a string that is surrounded by "! and replace the first "!" with a "!_".

For example: str(!test!).strip() -> str(!_test!).strip()

Here is the code I have so far:

print re.sub(r'!.*?!','!_', 'str(!test!).strip()')

With this code I grab too much and the result is: str(!_).strip()

Any thoughts on how to zero in on the first "!". Or alternatively, is there a way to grab the string in the "!!" and then add "!_"+"!" arround that string?

print re.sub(r'!(?=.*?!)', '!_', 'str(!test!).strip()')

Uses a positive lookahead.

print re.sub(r'!(.*?)!', r'!_\1!', 'str(!test!).strip()')

Uses a backreference.

Exclude ! from the characters between the !s: use [^!] instead of .

Then, capture the part of the RE you want to keep with () , and in the replacement string, use \\1 to insert it again.

print re.sub(r'!([^!]*!)', r'!_\1', 'str(!test!).strip()')

您需要使用括号将“单词”的后半部分分组,并在替换字符串\\g<1>使用该组。

re.sub(r'!(.*?!)', '!_\g<1>', 'str(!test!).strip()')

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