使用LPeg re模块解析XML类型文件

我正在尝试学习LPeg的re模块,这是一次非常有趣的经历,特别是因为官方文档非常好。

然而,有些主题似乎在那里解释得很差。例如,named group capture构造:{:name: p :}

考虑以下示例,我不明白为什么它不匹配:

print(re.compile
  [[item <- ('<' {:tag: %w+!%w :} '>' item+ '</' =tag '>') / %w+!%w]]
  :match[[<person><name>James</name><address>Earth</address></person>]])

-- 输出nil

有人能帮我理解这里出了什么问题吗?我想了很多,似乎确实缺少一些重要的东西。

点赞
用户40691
用户40691

这是一个晚回答,但你可以尝试以下模式

result = re.compile[[
  item <- ({| %s* '<' {:tag: %w+ :} %s* '>' (item / %s* { (!(%s* '<') .)+ }) %s* '</' =tag '>' |})+
]]:match[[
<person>
    <name>
    James
    </name>
    <address>Earth</address>
</person>
]]

它使用表捕获来解析带有空格的 XML,以删除元素文本

tag = "person"
[1] = {
  tag = "name"
  [1] = "James"
}
[2] = {
  tag = "address"
  [1] = "Earth"
}
2015-12-26 22:08:55