How do I do a regex search in Nokogiri for text that matches a certain beginning?

此生再无相见时 提交于 2019-12-02 22:06:49
Aaron Patterson

Use the xpath function starts-with:

value.xpath('//p[starts-with(@id, "para-")]').each { |x| puts x['id'] }
insane.dreamer
divs = value.css('div[id^="para-"]')

And some docs you're seeking:

Nokogiri::XML::Node.send(:define_method, 'xpath_regex') { |*args|
  xpath = args[0]
  rgxp = /\/([a-z]+)\[@([a-z\-]+)~=\/(.*?)\/\]/
  xpath.gsub!(rgxp) { |s| m = s.match(rgxp); "/#{m[1]}[regex(.,'#{m[2]}','#{m[3]}')]" }
  self.xpath(xpath, Class.new {
    def regex node_set, attr, regex
      node_set.find_all { |node| node[attr] =~ /#{regex}/ }
    end
  }.new)
}

Usage:

divs = Nokogiri::HTML(page.root.to_html).
  xpath_regex("//div[@class~=/axtarget$/]//div[@class~=/^carbo/]")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!