URL Extraction with Regex

Extracting URLs from text using regular expressions

Python
import re

def extract_urls(text):
    pattern = r'https?://(?:www\.)?[\w\d\-]+\.[\w\d\-\.]+(?:/[\w\d\-\._~:/?#[\]@!$&\'()*+,;=]*)?' 
    return re.findall(pattern, text)

sample_text = "Check out https://www.example.com and http://subdomain.example.co.uk/page"
print("Sample Text:")
print(sample_text)
print()

urls = extract_urls(sample_text)
print("Extracted URLs:")
for url in urls:
    print(url)
Click Run or press shift + ENTER to run code.