【问题标题】:Why is my XPath with regex failing to match?为什么我的 XPath 与正则表达式不匹配?
【发布时间】:2020-04-27 14:40:27
【问题描述】:

如果包含格式为YYYY.M(M).D(D) 的日期,我想使用 Xidel 选择一个带有class="body"<section> 标签,以查找并提取一个包含8 个字符且可以包含字符和数字的特定字符串。

输入 HTML 示例:

<section class="body">
Start 2019.1.12

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

thi1te_t

</section>

命令:

xidel -s input.html -e "//*[@class='body' and contains(text(),'(20\d{2}).(\d{1,2}).(\d{1,2})')]"

由于某种原因,我无法让这个正则表达式工作。在regex101.com 上运行良好。

我想在最终输出中得到thi1te_t,可能使用正则表达式^.{8}$ 和grep。

【问题讨论】:

    标签: html regex xml xpath xidel


    【解决方案1】:

    使用匹配正则表达式的matches(),而不是测试文字子字符串包含的contains()

    我还建议使用. 而不是text(),因为它是您真正要匹配的元素的字符串值,而不是真正的text() 子节点。 p>


    总之,用于选择目标元素的 XPath 将是:

    //*[@class='body' and matches(text(),'(20\d{2}).(\d{1,2}).(\d{1,2})')]
    

    我想在最终输出中得到thi1te_t,可能使用正则表达式^.{8}$ 和grep。

    您可以通过标记与上述 XPath 匹配的元素的字符串值,然后选择与您的目标正则表达式匹配的行来返回该子字符串:

    tokenize(//*[@class='body' and matches(text(),'(20\d{2}).(\d{1,2}).(\d{1,2})')], 
            '\s*\n\s*')[matches(.,'^.{8}$')]
    

    此 XPath 表达式根据请求返回 thi1te_t

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多