代码之家  ›  专栏  ›  技术社区  ›  99miles

使用hpricot获取部分ref属性

  •  0
  • 99miles  · 技术社区  · 14 年前

    我想我需要一个hpricot和regex的组合。我需要搜索以“abc/”开头的“ref”属性的“a”标记,并返回后面的文本,直到下一个正斜杠“/”。

    所以,假设:

    <a href="/abc/12345/xyz123/">One</a>
    <a href="/abc/67890/xyzabc/">Two</a>
    

    12345年

    有人能帮忙吗?我一直在挣扎。

    3 回复  |  直到 14 年前
        1
  •  0
  •   the Tin Man    14 年前

    你不需要正则表达式,但你可以使用它。这里有两个例子,一个是使用regex,另一个是不使用Nokogiri,Nokogiri应该与Hpricot兼容,供您使用,并使用CSS访问器:

    require 'nokogiri'
    
    html = %q[
      <a href="/abc/12345/xyz123/">One</a>
      <a href="/abc/67890/xyzabc/">Two</a>
    ]
    
    doc = Nokogiri::HTML(html)
    doc.css('a[@href]').map{ |h| h['href'][/(\d+)/, 1] } # => ["12345", "67890"]
    doc.css('a[@href]').map{ |h| h['href'].split('/')[2] } # => ["12345", "67890"]
    
        2
  •  0
  •   vurte    14 年前

    或者使用regex:

    s = '<a href="/abc/12345/xyz123/">One</a>'
    s =~ /abc\/([^\/]*)/
    return $1
    
        3
  •  0
  •   user142019 user142019    14 年前

    把绳子分开怎么样 /

    (我不知道Hpricot,但据医生说):

    doc.search("a[@href]").each do |a|
        return a.somemethodtogettheattribute("href").split("/")[2]; // 2, because the string starts with '/'
    end