51 words, 1 min read

A quick tip on how to extract domain names from URLs and email addresses using Python:

import re
def extract_domain(input_string):
url_pattern = r'https?://(?:www\.)?([^/?]+)'
email_pattern = r'@([^@]+)'
url_match = re.search(url_pattern, input_string)
email_match = re.search(email_pattern, input_string)
if url_match:
return url_match.group(1)
elif email_match:
return email_match.group(1)
else:
return None
print(extract_domain('https://www.yellowduck.be')) # yellowduck.be
print(extract_domain('pieter@yellowduck.be')) # yellowduck.be