help in converting perl re to python re

E

eight02645999

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
 
J

Joel Hedlund

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)
 
S

Sybren Stuvel

Joel Hedlund enlightened us with:
regexp = re.compile(r"<(tag1)>(.*)</\1>")

I'd go for

regexp = re.compile(r"<(tag1)>(.*?)</\1>")

Otherwise this:

line = "<tag1>sometext</tag1><tag1>othertext</tag1>"
match = regexp.search(line)

will result in 'sometext</tag1><tag1>othertext'

Sybren
 
M

Mitja Trampus

i have some regular exp code in perl that i want to convert to python.
regexp = re.compile(r"<(tag1)>(.*)</\1>")
line = "<tag1>sometext</tag1>"
match = regexp.search(line)
if match:
variable = match.group(2)

Or, if you prefer shorter, quick-and-dirty syntax closer to perl's approach:

match = re.search(r"<(tag1)>(.*)</\1>", line)
if match: variable = match.group(2)
 

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

Similar Threads

Qns on blank lines 0
Converting swf to html5 2
re Questions 9
Re-using copyrighted code 2
RE Help splitting CVS data 7
Re for Apache log file format 4
Python battle game help 2
RE : Gnuplot 0

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top