正则表达式从URL中提取子域名?

dMi*_*Mix 13 regex

我有一堆域名来这样:

http://subdomain.example.com(example.com始终是example.com,但子域名不同).

我需要"子域名".

有耐心学习正则表达式的某些人可以帮助我吗?

Pan*_*m1c 41

上述正则表达式的问题在于:如果您不知道协议是什么,或者域名后缀是什么,您将得到一些意想不到的结果.这是针对这些情况的一点正则表达式.:d

/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i  //javascript
Run Code Online (Sandbox Code Playgroud)

这应该始终返回组1中的子域(如果存在).这里是一个Javascript示例,但它也适用于支持正向预测断言的任何其他引擎:

// EXAMPLE of use
var regex = /(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i
  , whoKnowsWhatItCouldBe = [
                        "www.mydomain.com/whatever/my-site" //matches: www
                      , "mydomain.com"// does not match
                      , "http://mydomain.com" // does not match
                      , "https://mydomain.com"// does not match
                      , "banana.com/somethingelse" // does not match
                      , "https://banana.com/somethingelse.org" // does not match
                      , "http://what-ever.mydomain.mu" //matches: what-ever
                      , "dev-www.thisdomain.com/whatever" // matches: dev-www
                      , "hot-MamaSitas.SomE_doma-in.au.xxx"//matches: hot-MamaSitas
                  , "http://hot-MamaSitas.SomE_doma-in.au.xxx" // matches: hot-MamaSitas
                  , "????.???????.ru" //even non english chars! Woohoo! matches: ????
                  , "???????.ru" //does not match
                  ];

// Run a loop and test it out.
for ( var i = 0, length = whoKnowsWhatItCouldBe.length; i < length; i++ ){
    var result = whoKnowsWhatItCouldBe[i].match(regex);
    if(result != null){
      // YAY! We have a match!
    } else {
      // Boo... No subdomain was found
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这显然是最好的答案,因为它可以解决协议,无/多个子域,并且与域无关. (4认同)
  • 这是最好的答案,绝对应该是公认的答案. (3认同)

Dra*_*mon 21

/(http:\/\/)?(([^.]+)\.)?domain\.com/
Run Code Online (Sandbox Code Playgroud)

然后$ 3(或\ 3)将包含"subdomain"(如果提供了一个).

如果你想在第一组中拥有子域,并且你的正则表达式引擎支持非捕获组(害羞组),请按照palindrom的建议使用它:

/(?:http:\/\/)?(?:([^.]+)\.)?domain\.com/
Run Code Online (Sandbox Code Playgroud)


Fac*_*tic 6

纯子域字符串(结果为 $1):

^http://([^.]+)\.domain\.com
Run Code Online (Sandbox Code Playgroud)

设为http://可选(结果为 2 美元):

^(http://)?([^.]+)\.domain\.com
Run Code Online (Sandbox Code Playgroud)

使http://和 子域可选(结果为 $3):

(http://)?(([^.]+)\.)?domain\.com
Run Code Online (Sandbox Code Playgroud)