将域与URL匹配

时间:2013-10-07 09:16:15

标签: ruby

我需要检查URL是否与domain匹配 例如:

http://www.opera.com/docs/changelogs/mac/ 匹配: opera.com

http://www.amazon.co.uk/gp/feature.html%3Fie%3DUTF8%26docId%3D1000423923 47 配合 amazon.co.uk

并且这样做,我写了这个:

require 'net/http'

uri = URI('http://cran.r-url.org/bin/max/')
domain = 'r-url.org'

urlToMatch = uri.host
check = urlToMatch.match(domain)


if check
  print "match \n"
else
  print "not a match \n"
end

有更好的方法吗? 谢谢

2 个答案:

答案 0 :(得分:3)

require 'uri'

def url_on_domain?(url, domain)
  URI.parse(url).host.match(domain)
end

if url_on_domain?('http://cran.r-url.org/bin/max/', 'r-url.org')
  print "match \n"
else
  print "not a match \n"
end

答案 1 :(得分:0)

require 'uri'

domain = 'r-url.org'
check = URI.parse('http://cran.r-url.org/bin/max/').host == domain

if check
  print "match \n"
else
  print "not a match \n"
end