Extract URLs from text with regex in Python

Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

14 lines
Python 3.9+
import re

text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""

url_pattern = r'https?://[^\s]+'

urls = re.findall(url_pattern, text)

for url in urls:
    print(url)

Output

stdout
https://www.example.com
http://localhost:8000/api

How it works

The regex pattern https?://[^\s]+ matches the literal 'http', an optional 's', '://', then any non-whitespace characters. re.findall scans the entire text and returns every non-overlapping match as a list. The loop prints each URL on its own line. This pattern works for many common URLs but may include trailing punctuation.

Common mistakes

  • Forgetting to import the `re` module
  • Using a pattern that captures trailing punctuation like '.' or ')'
  • Assuming the pattern matches ftp:// or other protocols

Variations

  1. Adjust pattern to `(?:https?|ftp)://[^\s]+` to include FTP URLs
  2. Use `re.finditer` to get match objects with positions in the text

Real-world use cases

  • Scanning log files to extract external links for security analysis.
  • Parsing user-generated content to detect and linkify URLs in a web app.
  • Extracting API endpoints from configuration or documentation text.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.