我试图不匹配后面或前面有 XML 标记的单词。
import re
strTest = "<random xml>hello this was successful price<random xml>"
for c in re.finditer(r'(?<![<>])(\b\w+\b)(?<!=[<>])(\W+)',strTest):
c1 = c.group(1)
c2 = c.group(2)
if ('<' != c2[0]) and ('<' != c.group(1)[len(c.group(1))-1]):
print c1
结果是:
xml
this
was
successful
xml
想要的结果:
this
was
successful
我一直在尝试否定前瞻和否定回顾断言。我不确定这是否是正确的方法,如有任何帮助,我将不胜感激。
请您参考如下方法:
首先,直接回答你的问题:
我通过检查由包含(主要)字母或“<”或“>”的一系列字符组成的每个“单词”来做到这一点。当正则表达式将它们提供给 some_only 时,我寻找后两个字符之一。如果两者都没有出现,我打印“单词”。
>>> import re
>>> strTest = "<random xml>hello this was successful price<random xml>"
>>> def some_only(matchobj):
... if '<' in matchobj.group() or '>' in matchobj.group():
... pass
... else:
... print (matchobj.group())
... pass
...
>>> ignore = re.sub(r'[<>\w]+', some_only, strTest)
this
was
successful
这适用于您的测试字符串;然而,正如其他人已经提到的,在 xml 上使用正则表达式通常会导致很多问题。
为了使用更传统的方法,我必须清除该 xml 字符串中的几个错误,即将 random xml 更改为 random_xml 并使用正确的结束符标签。
我更喜欢使用 lxml 库。
>>> strTest = "<random_xml>hello this was successful price</random_xml>"
>>> from lxml import etree
>>> tree = etree.fromstring(strTest)
>>> tree.text
'hello this was successful price'
>>> tree.text.split(' ')[1:-1]
['hello', 'this', 'was', 'successful', 'price']
>>> tree.text.split(' ')[1:-1]
['this', 'was', 'successful']
