在两个值之间提取文本的正则表达式是什么?
在:
<office:annotation office:name="__Annotation__45582_97049284">
</office:annotation>
case 1 there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__45582_97049284"/>
<office:annotation office:name="__Annotation__19324994_2345354">
</office:annotation>
case 2there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__19324994_2345354"/>
出:
list = [
'case 1 there can be an arbitrary text with any symbols',
'case 2 there can be an arbitrary text with any symbols',
]
答案 0 :(得分:3)
使用XML解析器更好,如果你想要一个正则表达式解决方案,那么试试下面的,
>>> str = """<office:annotation office:name="__Annotation__45582_97049284">
... </office:annotation>
... case 1 there can be an arbitrary text with any symbols
... <office:annotation-end office:name="__Annotation__45582_97049284"/>
...
... <office:annotation office:name="__Annotation__19324994_2345354">
... </office:annotation>
... case 2there can be an arbitrary text with any symbols
... <office:annotation-end office:name="__Annotation__19324994_2345354"/>"""
>>> m = re.findall(r'<\/office:annotation>\s*(.*)(?=\n<office:annotation-end)', str)
>>> m
['case 1 there can be an arbitrary text with any symbols', 'case 2there can be an arbitrary text with any symbols']
OR
一个更好的正则表达式,
<\/office:annotation>([\w\W\s]*?)(?=\n?<office:annotation-end)
答案 1 :(得分:0)
由于这是一个命名空间的XML文档,因此在选择节点时必须处理这些命名空间。有关详细信息,请参阅this answer。
以下是使用lxml
和xpath
表达式解析它的方法:
<强> data.xml中强>
<?xml version='1.0' encoding='UTF-8'?>
<document xmlns:office="http://www.example.org/office">
<office:annotation office:name="__Annotation__45582_97049284">
</office:annotation>
case 1 there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__45582_97049284"/>
<office:annotation office:name="__Annotation__19324994_2345354">
</office:annotation>
case 2there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__19324994_2345354"/>
</document>
<强> parse.py 强>
from lxml import etree
tree = etree.parse('data.xml')
root = tree.getroot()
nsmap = root.nsmap
annotations = root.xpath('//office:annotation', namespaces=nsmap)
comments = []
for annotation in annotations:
comment = annotation.tail.strip()
comments.append(comment)
print comments
输出:
['case 1 there can be an arbitrary text with any symbols',
'case 2there can be an arbitrary text with any symbols']
答案 2 :(得分:0)
>>> regex = re.compile(r'</.+>\s*(.+)\s*<.+>')
>>> matched = re.findall(regex, text)
>>> print(matched)
['case 1 there can be an arbitrary text with any symbols', 'case 2there can be an arbitrary text with any symbols']
编辑:我们走了。呸..这些编辑点。