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 "!_"+"!" arr开发者_运维技巧ound that string?
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()')
print re.sub(r'!(?=.*?!)', '!_', 'str(!test!).strip()')
Uses a positive lookahead.
print re.sub(r'!(.*?)!', r'!_\1!', 'str(!test!).strip()')
Uses a backreference.
You need to group the second half of the "word" with parenthesis and use the group in your substitute string \g<1>
.
re.sub(r'!(.*?!)', '!_\g<1>', 'str(!test!).strip()')
精彩评论