正则表达式从链接URL获取ID

时间:2013-08-26 07:17:00

标签: ruby regex nokogiri

我有这样的链接:

<div class="zg_title">
  <a href="https://rads.stackoverflow.com/amzn/click/com/B000O3GCFU" rel="nofollow noreferrer">Thermos Foogo Leak-Proof Stainless St...</a>     
</div>

我正在这样抓他们:

  product_asin = product.xpath('//div[@class="zg_title"]/a/@href').first.value 

问题在于它占用了整个网址而我只想获取ID:

B000O3GCFU

我想我需要做这样的事情:

product_asin = product.xpath('//div[@class="zg_title"]/a/@href').first.value[ReGEX_HERE]

在这种情况下,我可以使用的最简单的正则表达式是什么?

修改

奇怪,链接网址似乎不完整:

http://www.amazon.com/Thermos-Foogo-Leak-Proof-Stainless-10-Ounce/dp/B000O3GCFU/ref=zg_bs_baby-products_1

3 个答案:

答案 0 :(得分:3)

使用/\w+$/

p doc.xpath('//div[@class="zg_title"]/a/@href').first.value[/\w+$/]

/\w+$/匹配尾随字母,数字_


require 'nokogiri'

s = <<EOF
<div class="zg_title">
  <a href="http://rads.stackoverflow.com/amzn/click/B000O3GCFU">Thermos Foogo Leak-Proof Stainless St...</a>     
</div>
EOF

doc = Nokogiri::HTML(s)
p doc.xpath('//div[@class="zg_title"]/a/@href').first.value[/\w+$/]
# => "B000O3GCFU"

答案 1 :(得分:3)

鉴于产品代码始终以/dp/开头,后跟/

url[/(?<=\/dp\/)[^\/]+/]

或者,或许更具可读性:

url[%r{(?<=/dp/)[^/]+}]

或者,不使用正则表达式:

parts = url.split('/')
parts[parts.index('dp') + 1]

答案 2 :(得分:0)

基于可用解析器的方法(取悦Nicolas Tyler或其他任何宁愿在这种情况下避免使用正则表达式进行解析的人)

require 'uri'

product_uri = product.xpath('//div[@class="zg_title"]/a/@href').first.value
# e.g. http://www.amazon.com/Thermos-Foogo-Leak-Proof-Stainless-10-Ounce/dp/B000O3GCFU/ref=zg_bs_baby-products_1

product_path = URI.parse( product_asin_uri ).path.split('/')
# => ["", "Thermos-Foogo-Leak-Proof-Stainless-10-Ounce", 
#     "dp", "B000O3GCFU", "ref=zg_bs_baby-products_1"]

# This relies on (un-researched assumption) location in path being consistent
# Now we have components though, we can look at Amazon's documentation and 
# select based on position in path, relative position from some other identifier
# etc, without risk of a regex mismatch

product_asin = product_path[2]
# => "B000O3GCFU"