Find pattern in xml string
I have fol开发者_高级运维lowing 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?
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 or a more general discussion here), and not regular expressions. Accurately parsing XML by mean of regex is actually not possible, 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 instead.
精彩评论