python - Replacing only the captured group using re.sub and multiple replacements -


below simple example i've created.

string = 'i love sleeping. love singing. love dancing.' pattern =re.compile(r'i love (\w+)\.') 

i want replace (\w+) portion re.sub.
question in 2 parts:

i want replace (\w+), without having resort groups capture rest of text.

so don't want like:

pattern =re.compile(r'(i) (love) (\w+)\.') re.sub(pattern, r'/1 /2 swimming', string) 

because may unreliable when working huge amounts of text , optional groups.

second part:

since have 3 matches, possible feed in list re.sub iterate through list each match , make sub accordingly. in words, want each item of list ['swimming, eating, jogging'] sync matches, (like method zip) , make substitution.

so output should (even single total output fine:

'i love swimming' 'i love eating' 'i love jogging' 

you can use lookbehind , lookahead based regex , lambda function iterate through replacements words:

>>> words = ['swimming', 'eating', 'jogging'] >>> pattern = re.compile(r'(?<=i love )\w+(?=\.)') >>> print pattern.sub(lambda m: words.pop(0), string) 'i love swimming. love eating. love jogging.' 

code demo


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -