-3

What need a template RegEx to get a domain name.

For example, i have:

lifenews.ru
www.forbes.com
goo.gl
ya.ru

and get:

lifenews
forbes
goo
ya

3 Answers3

1

How about:

^(?:.*(?=\..*\..*).)?([^.]+)

Demo on regex101.

The first part ((?:.*(?=\..*\..*).)?) will consume everything before (a sequence of words with two dots, like) abc.com in www.stuff.abc.com. The next part (([^.]+)) matches abc.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • 1
    This will fail on domains in countries which use multiple levels, such as [BBC](http://www.bbc.co.uk) or [New South Wales](http://www.nsw.gov.au/) – ClickRick May 03 '14 at 16:42
  • @ClickRick You are right. I didn't have those cases in mind - didnt think, mistakenly, that was the intention of the question. A regex to predict those cases, though, without enumerating them (as the accepted answer does, or the answer in the marked-as-duplicate question) is not possible. Cheers! – acdcjunior May 03 '14 at 21:17
0

Javascript w/o regex:

var parts = "www.forbes.com".split('.');
parts.pop();//first level domain
var domain = parts.pop(); //second level domain
vp_arth
  • 14,461
  • 4
  • 37
  • 66
0
preg_match('/(?:www\.)?(\w+)\./', $url, $matches);
$host = $matches[1];

This works and, as far as I can tell, it accounts for someone putting www or not.

  • This assumes that the part of the domain name of interest will either be the first or will follow a `www.`. – ClickRick May 03 '14 at 16:41