[Regex] Search and replace?

G

Gilles Ganault

Hello

I need to iterate through a variable, and for each pattern that
matches, replace this with something else.

I read the chapter in www.amk.ca/python/howto/regex/, but the output
is wrong:

=======
#Extract two bits, and rewrite the HTML
person = re.compile('<tr onMouseOver=(?P<item1>.+?)>.+?<a
onmouseover="Tip(?P<item2>.+?)&nbsp;</td>')

output = person.sub('<tr onMouseOver=\1><td><a
onmouseover="Tip\2</td>', input)
=======

Does someone have a simple example handy so I can check what's wrong
with the above?

Thank you.
 
S

Sion Arrowsmith

Gilles Ganault said:
#Extract two bits, and rewrite the HTML
person = re.compile('<tr onMouseOver=(?P<item1>.+?)>.+?<a onmouseover="Tip(?P<item2>.+?)&nbsp;</td>')

output = person.sub('<tr onMouseOver=\1><td><a onmouseover="Tip\2</td>', input)

Does someone have a simple example handy so I can check what's wrong
with the above?

Do you have an example of the input string which you're using? And
exactly how the output is "wrong"? At a wild guess, you mean your
substitution string to be:

'<tr onMouseOver=\\1><td><a onmouseover="Tip\\2</td>' or
r'<tr onMouseOver=\1><td><a onmouseover="Tip\2</td>'

(note the backslash escaping).

Oh, and don't use "input" as a name -- you're shadowing the builtin
input function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top