regular expressions, substituting and adding in one step?

John Salerno johnjsal at NOSPAMgmail.com
Mon May 8 16:33:02 CEST 2006


Ok, this might look familiar. I'd like to use regular expressions to 
change this line:

self.source += '<p>' + paragraph + '</p>\n\n'

to read:

self.source += '<p>%s</p>\n\n' % paragraph

Now, matching the middle part and replacing it with '%s' is easy, but 
how would I add the extra string to the end of the line? Is it done all 
at once, or must I make a new regex to match?

Also, I figure I'd use a group to match the word 'paragraph', and use 
that group to insert the word at the end, but how will I 'retain' the 
state of \1 if I use more than one regex to do this?

I'd like to do this for several lines, so I'm trying not to make it too 
specific (i.e., matching the entire line, for example, and then adding 
text after it, if that's possible).

So the questions are, how do you use regular expressions to add text to 
the end of a line, even if you aren't matching the end of the line in 
the first place? Or does that entail using separate regexes that *do* do 
this? If the latter, how do I retain the value of the groups taken from 
the first re?

Thanks, hope that made some sense.



More information about the Python-list mailing list