[Regex] Search and replace?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gilles Ganault

    [Regex] Search and replace?

    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="Ti p(?P<item2>.+?) &nbsp;</td>')

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

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

    Thank you.
  • Sion Arrowsmith

    #2
    Re: [Regex] Search and replace?

    Gilles Ganault <nospam@nospam. comwrote:
    >#Extract two bits, and rewrite the HTML
    >person = re.compile('<tr onMouseOver=(?P <item1>.+?)>.+? <a onmouseover="Ti p(?P<item2>.+?) &nbsp;</td>')
    >
    >output = person.sub('<tr onMouseOver=\1> <td><a onmouseover="Ti p\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="Ti p\\2</td>' or
    r'<tr onMouseOver=\1> <td><a onmouseover="Ti p\2</td>'

    (note the backslash escaping).

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

    --
    \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
    "Frankly I have no feelings towards penguins one way or the other"
    -- Arthur C. Clarke
    her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

    Comment

    Working...