Find pattern in xml string
Question: I have following xml tags in my xml file as follows '''

`<pd:link scheme="http://www.w3.org/1999/xhtml" target="www.altruvest.org
<pd:unicode ch="2014"/> or <pd:unicode ch="2014"/>
www.Boardmatch.org">"www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode
ch="2014"/> www.Boardmatch.org</pd:link>)` '''

in above tag pd:unicode tag is inside text value of target. I want to create
regular expression pattern to find such tag where tag is within text in
python.

Can anyone please help to create pattern for this?


Answer: Edited answer:

    
    
    >>> s = r'"<pd:link scheme="http://www.w3.org/1999/xhtml" target="www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org">www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org</pd:link>"'
    >>> import re
    >>> r = re.search(r'=".*?(<pd:unicode ch="\d+"/>).*?"', s, re.DOTALL)
    >>> r.groups()
    ('<pd:unicode ch="2014"/>',)
    

What the above does is to match the `pd:unicode` tags when they are preceded
by a `="` and followed by `"`. The `re.DOTALL` ignores newlines (treats them
as normal characters).

Bare in mind that what you are asking to do is _parsing_ XML, something for
which you should use an xmlparser (see for example
[xml.etree](http://docs.python.org/library/xml.etree.elementtree.html) or a
more general discussion [here](http://wiki.python.org/moin/PythonXml)), and
not regular expressions. Accurately parsing XML by mean of regex is actually
[not possible](http://stackoverflow.com/q/6751105/146792), so the above regex
is likely to generate false positives or to miss some true ones.

If you don't want to go with a full XML parser, you could consider something
like [pyparsing](http://pyparsing.wikispaces.com/) instead.

