有些时候,需要提取域名的根域名,如:
 
baidu.com             的根域名是baidu.com
wenku.baidu.com  的根域名是baidu.com
 
对于URL,可以先进行字符串的预处理,分割出域名,再进行处理。

 
下面是go实现的代码:(正则里的域名后缀只列出了一部分)

go
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
package main import ( "fmt" "github.com/prometheus/common/log" "regexp" ) func main(){ str := "123.com" //要进行匹配的域名 _, err := regexp.MatchString("(\\w*\\.?){1}\\.(com.cn|net.cn|gov.cn|org\\.nz|org.cn|com|net|org|gov|cc|biz|info|cn|co)$", str) if err != nil { log.Fatal("Match error: ",err.Error()) } reg := regexp.MustCompile("(\\w*\\.?){1}\\.(com.cn|net.cn|gov.cn|org\\.nz|org.cn|com|net|org|gov|cc|biz|info|cn|co)$") data := reg.Find([]byte(str)) fmt.Println(string(data)) }

如有不对,烦请指出,感谢!