Regular expression question

John Hunter jdhunter at nitace.bsd.uchicago.edu
Wed May 8 09:53:18 EDT 2002


>>>>> "Patrick" == Patrick Gaherty <pgaherty at chambersharrap.co.uk> writes:

    Patrick> Im performing the following search and replace in
    Patrick> Python. However, I would like to return the first group
    Patrick> as lowercase using .lower() in the replacement string,
    Patrick> What's the best way of achieving this?


There may be a better way, but I think this does what you want.  My
guess is that you'll want to do a lot of these replaces so I compiled
in the regex.  Also, you can use """ to avoid having to \ quote the
other quotes in your strings.

result = """<TABLE NAME="MYTABLE"><tr><th>Name</th><td>John Hunter</td></tr></TABLE>"""

rgx = re.compile('<TABLE NAME="(.*?)">(.*?)</TABLE>')
match = rgx.match( result )
if match:
    result = """<a href="javascript:openWin('images/%s.htm');">%s</a>""" \
             % (match.group(1).lower(), match.group(2))

    
print result


Prints:
<a href="javascript:openWin('images/mytable.htm');"><tr><th>Name</th><td>John Hunter</td></tr></a>



More information about the Python-list mailing list