469,328 Members | 1,265 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,328 developers. It's quick & easy.

Re: Python regex question

Tim van der Leeuw wrote:

I'm trying to create a regular expression for matching some particular
XML strings. I want to extract the contents of a particular XML tag,
only if it follows one tag, but not follows another tag. Complicating
this, is that there can be any number of other tags in between. [...]
Sounds like this would be easier to implement using Python's SAX API.

Here's a short example that does something similar to what you want to

import xml.sax

test_str = """
<foo x="1" y="2"/>
<foo x="3" y="4"/>

class MyHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.ignore_next = False

def startElement(self, name, attrs):
if name == "ignore":
self.ignore_next = True
elif name == "foo":
if not self.ignore_next:
# handle the element you're interested in here
print "MY ELEMENT", name, "with", dict(attrs)

self.ignore_next = False

xml.sax.parseString(test_str, MyHandler())

In this case, this looks much clearer and easier to understand to me
than regular expressions.

-- Gerhard

Jun 27 '08 #1
0 606

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

17 posts views Thread by Michael McGarry | last post: by
5 posts views Thread by Vamsee Krishna Gomatam | last post: by
3 posts views Thread by gisleyt | last post: by
10 posts views Thread by Raymond | last post: by
3 posts views Thread by Walter Cruz | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by Purva khokhar | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.