Created
April 7, 2023 11:09
-
-
Save MOOOWOOO/a8e714bbf66e44d5755ceb5bce474510 to your computer and use it in GitHub Desktop.
extract domain name from an URL likely string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def extract_domain_name(url): | |
""" | |
Given a URL string, returns the domain name without the TLD (top-level domain), | |
or an empty string if the input is invalid. | |
""" | |
if not isinstance(url, str): | |
return "" | |
url = url.strip().lower() | |
pattern = r"(?:http[s]?://)?(?:www\.)?([^./]+)(?:\.[^./]+)*\.?(?:/[^/]*)?$" | |
match = re.search(pattern, url) | |
if not match: | |
return "" | |
return match.group(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from extract_domain_name import extract_domain_name | |
test_cases = ['http://www.example.com', | |
'http://www.example.cc/ad', | |
'www.example.net', | |
'www.example.net/ad', | |
'example.xyz/ad', | |
'example.com.cn', | |
'.example.org', | |
'.example.com/ad', | |
'example.', | |
'.example', | |
'.example.', | |
'example'] | |
for test_case in test_cases: | |
domain_name = extract_domain_name(test_case) | |
print(f'{test_case}: {domain_name}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment