regular expressions, substituting and adding in one step?

John Salerno johnjsal at NOSPAMgmail.com
Mon May 8 10:52:01 EDT 2006


John Salerno wrote:

> 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?

Here's what I have so far:

-----------

import re

txt_file = open(r'C:\Python24\myscripts\re_test.txt')
new_string = re.sub(r"' \+ ([a-z]+) \+ '", '%s', txt_file.read())
new_string = re.sub(r'$', ' % paragraph', new_string)
txt_file.close()

-----------

re_test.txt contains:

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

Both substitutions work, but now I just need to figure out how to 
replace the hard-coded ' % paragraph' parameter with something that uses 
the group taken from the first regex. I'm guessing if I don't use it at 
that time, then it's lost. I suppose I could create a MatchObject and 
save group(1) as a variable for later use, but that would be a lot of 
extra steps, so I wanted to see if there's a way to do it all at one 
time with regular expressions.

Thanks.



More information about the Python-list mailing list