Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract the domain from a URL

I need to extract domain (four.five) from URL (one.two.three.four.five) in a Lua string variable.

I can't seem to find a function to do this in Lua.

EDIT:

By the time the URL gets to me, the http stuff has already been stripped off. So, some examples are:

a) safebrowsing.google.com 
b) i2.cdn.turner.com 
c) powerdns.13854.n7.nabble.com 

so my result should be:

a) google.com
b) turner.com
c) nabble.com
like image 631
Xi Vix Avatar asked Sep 12 '13 22:09

Xi Vix


2 Answers

This should work:

local url = "foo.bar.google.com"
local domain = url:match("[%w%.]*%.(%w+%.%w+)")
print(domain)       

Output:google.com

The pattern [%w%.]*%.(%w+%.%w+) looks for the content after the second dot . from the end.

like image 95
Yu Hao Avatar answered Nov 11 '22 10:11

Yu Hao


local url = "http://foo.bar.com/?query"
print(url:match('^%w+://([^/]+)')) -- foo.bar.com

This pattern '^%w+://([^/]+)' means: ^ from the beginning of the line, take %w+ one or more alphanumeric characters (this is the protocol), then ://, then [^/]+ 1 or more characters other than slash and return (capture) these characters as the result.

like image 43
Paul Kulchenko Avatar answered Nov 11 '22 11:11

Paul Kulchenko