【每日一题0815】提取主域名

:woman_mage:给定一个字符串格式的URL完整地址,请编写一个python函数,提取出其中的主域。

示例:
输入:"http://ceshiren.com/stde/courses" ,输出:"ceshiren"
输入:"https://www.hogwarts.com" ,输出:"hogwarts"

题目难度:简单
题目来源:codewars

def domain_name(s:str) -> str:
    pass
  
assert domain_name("http://ceshiren.com/stde/courses") == "ceshiren" 
assert domain_name("https://www.hogwarts.com") == "hogwarts"
import  tldextract # pip install tldextract

def domain_name(s: str) -> str:
    return  tldextract.extract(s).domain

assert domain_name("http://ceshiren.com/stde/courses") == "ceshiren"
assert domain_name("https://www.hogwarts.com") == "hogwarts"
import re


def domain_name(s: str) -> str:
    res = re.findall(r'.*?://[w.]*\.?(.*?)\..*?', s)
    return res[0]


assert domain_name("http://ceshiren.com/stde/courses") == "ceshiren"
assert domain_name("https://www.hogwarts.com") == "hogwarts"
def domain_name(s: str) -> str:
    for i in urlparse(s).netloc.split("."):
        if i == "www":
            continue
        else:
            return i


assert domain_name("http://ceshiren.com/stde/courses") == "ceshiren"
assert domain_name("https://www.hogwarts.com") == "hogwarts"
def domain_name(s:str):
    res=tldextract.extract(s)
    return res.domain

image

参考题解1

def domain_name(s:str) -> str
    return s.split("//")[-1].split("www.")[-1].split(".")[0]

思路:利用字符串内置的split方法进行分割解析,每次取分割后所需的部分。

参考题解2

import re

def domain_name(s:str):
    return re.search('(https?://)?(www\d?\.)?(?P<name>[\w-]+)\.', s).group('name')

思路:利用正则表达式语法提取目标信息。