html - 为什么我的 XPath 与正则表达式无法匹配?

标签 html regex xml xpath xidel

我想用 Xidel 来选择 <section>class="body" 标记如果包含格式为 YYYY.M(M).D(D) 的日期查找并提取一个特定的字符串,该字符串有 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。

最佳答案

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

我还建议使用 . 而不是 text() 因为它是您要匹配的真正目标的元素的 string value ,不是真正的 text() 节点子节点。


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

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

I would like to get thi1te_t in the final output, probably with regex ^.{8}$ and 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

关于html - 为什么我的 XPath 与正则表达式无法匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59673337/

相关文章:

regex - perl 匹配关键字并修改关键字

php - 来自页面标题字段的 JavaScript clean-URL

java - 在 SimpleXML 注释中指定集合类型

android - 找不到与给定名称匹配的资源(在 'layout_above' 处,值为 '@id/adView' )。即使在 AdView 拥有该 ID 之后

ruby - Nokogiri - 使用 XML,而不是 HTML

javascript - jQuery - ("a.class")加载和window.open?

javascript - 在 Javascript 中折叠和伸展树(Splay Tree)结构

JQuery Dimmer 和 No Scrolling 不能一起工作

javascript - 如何在多个 Canvas html5上绘制圆圈?

regex - 删除Powershell中具有非英语字符的行