help in converting perl re to python re

Joel Hedlund joel.hedlund at gmail.com
Fri Mar 3 09:04:16 CET 2006


Hi


> the perl code finds a line that matches something like
> "<tag1>sometext<\tag1>" in the line and then assign $variable the value
> of  "sometext"

No, but if you use a closing </tag1> instead of <\tag1> it does. You had me scratching my head for a while there. :-)

This should do it in python:

------------------------------------------------
#!/usr/bin/python

import re

regexp = re.compile(r"<(tag1)>(.*)</\1>")
line = "<tag1>sometext</tag1>"
match = regexp.search(line) 

if match:
    variable = match.group(2)

------------------------------------------------

Good luck!
/Joel Hedlund


eight02645999 at yahoo.com wrote:
> hi
> 
> i have some regular exp code in perl that i want to convert to python.
> 
> 
> if $line =~ m#<(tag1)>(.*)</\1>#
>    {
>      $variable = $2;
>     }
> 
> the perl code finds a line that matches something like
> 
> "<tag1>sometext<\tag1>" in the line and then assign $variable the value
> of  "sometext"
> 
> how can i do an equivalent of that using re module?
> thanks
> 



More information about the Python-list mailing list