Skip to content

Instantly share code, notes, and snippets.

@tastycode
Created January 26, 2013 23:22
Show Gist options
  • Save tastycode/4645269 to your computer and use it in GitHub Desktop.
Save tastycode/4645269 to your computer and use it in GitHub Desktop.
url = "http://www.google.com"
rex = %r{^(\w+)*://(\w+)?\.(\w+).?\.(\w+)}
url.match(rex)
url_data = {:host => $1, :hostname => $2, :domain => $3, :tld => $4}
p url_data # {:host=>"http", :hostname=>"www", :domain=>"google", :tld=>"com"}
url = "http://www.google.com"
rex = %r{
^
(\w+)* # protocol
://
(\w+)? # hostname
\.
(\w+)? # domain
\.
(\w+) # tld
}x
url.match(rex)
url_data = {:host => $1, :hostname => $2, :domain => $3, :tld => $4}
p url_data # {:host=>"http", :hostname=>"www", :domain=>"google", :tld=>"com"}
url = "http://www.google.com"
rex = %r{
^ #starts with
(?<protocol>\w+)* #either a protocol or not
://
(?<hostname>\w+)?
\.
(?<domain>\w+)?
\.
(?<tld>\w+)?
}x
result = url.match(rex)
p result # #<MatchData "http://www.google.com" protocol:"http" hostname:"www" domain:"google" tld:"com">
require 'ostruct'
url = "http://www.google.com"
rex = %r{
^ #starts with
(?<protocol>\w+)* #either a protocol or not
://
(?<hostname>\w+)?
\.
(?<domain>\w+)?
\.
(?<tld>\w+)?
}x
result = url.match(rex)
class MatchData
def to_hash
Hash[*names.zip(captures).flatten]
end
end
URL = Class.new(OpenStruct)
url = URL.new(result.to_hash)
p url # #<URL protocol="http", hostname="www", domain="google", tld="com">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment