【问题标题】:Parsing XML-type file with LPeg re module使用 LPeg re 模块解析 XML 类型的文件
【发布时间】:2015-08-12 20:14:58
【问题描述】:

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

但是,有些主题似乎没有得到很好的解释。例如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>]])

-- outputs nil

谁能帮我理解这里出了什么问题?我想了很多,但似乎我确实错过了一些重要的东西。

【问题讨论】:

    标签: xml lua pattern-matching lpeg


    【解决方案1】:

    这是一个较晚的答案,但您可以尝试以下模式

    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"
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2013-08-22
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多