代码之家  ›  专栏  ›  技术社区  ›  bcolfer

如何在Nokogiri中对匹配某个开头的文本进行正则表达式搜索?

  •  24
  • bcolfer  · 技术社区  · 15 年前

    鉴于:

    require 'rubygems'
    require 'nokogiri'
    value = Nokogiri::HTML.parse(<<-HTML_END)
    "<html>
    <body>
      <p id='para-1'>A</p>
      <div class='block' id='X1'>
        <h1>Foo</h1>
        <p id='para-2'>B</p>
      </div>
      <p id='para-3'>C</p>
      <h2>Bar</h2>
      <p id='para-4'>D</p>
      <p id='para-5'>E</p>
      <div class='block' id='X2'>
        <p id='para-6'>F</p>
      </div>
    </body>
    </html>"
    HTML_END
    

    divs = value.search('//div[@id^="para-"]')
    
    1. 如何对XPath样式的元素进行模式搜索?
    4 回复  |  直到 9 年前
        1
  •  74
  •   the Tin Man    12 年前

    使用xpath函数 starts-with :

    value.xpath('//p[starts-with(@id, "para-")]').each { |x| puts x['id'] }
    
        2
  •  19
  •   the Tin Man    12 年前
    divs = value.css('div[id^="para-"]')
    
        3
  •  3
  •   andre-r    11 年前

    以及您正在寻找的一些文档:

        4
  •  1
  •   karwan    9 年前
    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)
    }
    

    divs = Nokogiri::HTML(page.root.to_html).
      xpath_regex("//div[@class~=/axtarget$/]//div[@class~=/^carbo/]")
    
    推荐文章