加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 用于正则表达式匹配的xpath表达式?

发布时间:2020-12-16 19:45:15 所属栏目:百科 来源:网络整理
导读:我想要搜索具有某种模式的html文档中的div id. 我想在正则表达式中匹配这个模式: foo_([[:digit:]]{1.8}) 使用xpath.上述模式的xpath相当于什么? 我被卡在// div [@ id =“foo_然后什么?如果有人可以继续为其表达法律. 编辑 对不起,我想我必须详细说明一
我想要搜索具有某种模式的html文档中的div id.
我想在正则表达式中匹配这个模式:
foo_([[:digit:]]{1.8})

使用xpath.上述模式的xpath相当于什么?

我被卡在// div [@ id =“foo_然后什么?如果有人可以继续为其表达法律.

编辑

对不起,我想我必须详细说明一下.其实不是foo_,它是post_message_

Btw,我用机械/ nokogiri(红宝石)

这是代码段:

html_doc = Nokogiri::HTML(open(myfile))
message_div =  html_doc.xpath('//div[substring(@id,13) = "post_message_" and substring-after(@id,"post_message_") => 0 and substring-after(@id,"post_message_") <= 99999999]')

仍然失败错误信息:

Couldn’t evaluate expression ‘//div[substring(@id,"post_message_") <= 99999999]‘ (Nokogiri::XML::XPath::SyntaxError)

解决方法

这个怎么样(更新):

XPath 1.0:

"//div[substring-before(@id,'_') = 'foo' 
       and substring-after(@id,'_') >= 0 
       and substring-after(@id,'_') <= 99999999]"

编辑#2:OP对问题进行了更改.以下,XPath 1.0表达式更为简化:

"//div[substring(@id,1,13) = 'post_message_' 
       and substring(@id,14) >= 0 
       and substring(@id,14) <= 99999999]"

XPath 2.0有一个方便的matches() function:

"//div[matches(@id,'^foo_d{1,8}$')]"

除了更好的可移植性,我希望数值表达式(XPath 1.0样式)的表现要好于正则表达式测试,尽管这只会在处理大数据集时变得明显.

原始版本的答案:

"//div[substring-before(@id,'_') = 'foo' 
       and number(substring-after(@id,'_')) = substring-after(@id,'_') 
       and number(substring-after(@id,'_')) &gt;= 0 
       and number(substring-after(@id,'_')) &lt;= 99999999]"

使用number()函数是不必要的,因为数学比较运算符隐含地将它们的参数强制转换为数字,任何非数字将变为NaN,并且大于/小于测试将失败.

我还删除了尖括号的编码,因为这是XML要求,而不是XPath要求.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读