Parse WHOIS Data with Python Regex

Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Python code

39 lines
Python 3.9+
import re
from datetime import datetime


def parse_whois(whois_text: str) -> dict:
    """Extract key registration fields from a mock WHOIS record."""
    patterns = {
        "domain": r"Domain Name:\s*(.+)",
        "registrar": r"Registrar:\s*(.+)",
        "creation_date": r"Creation Date:\s*(.+)",
        "expiry_date": r"Expiry Date:\s*(.+)",
        "status": r"Status:\s*(.+)",
    }
    parsed = {}
    for key, pattern in patterns.items():
        match = re.search(pattern, whois_text, re.IGNORECASE)
        if match:
            parsed[key] = match.group(1).strip()
    return parsed


def days_until_expiry(expiry_date_str: str) -> int:
    """Return days remaining until domain expiry."""
    expiry = datetime.strptime(expiry_date_str, "%Y-%m-%d")
    return (expiry - datetime.now()).days


if __name__ == "__main__":
    mock_whois = """Domain Name: example.com
    Registrar: Mock Registrar LLC
    Creation Date: 2015-06-01
    Expiry Date: 2025-06-01
    Status: clientTransferProhibited"""

    info = parse_whois(mock_whois)
    print(f"Domain: {info['domain']}")
    print(f"Registrar: {info['registrar']}")
    print(f"Expires in: {days_until_expiry(info['expiry_date'])} days")
    print(f"Status: {info['status']}")

Output

stdout
Domain: example.com
Registrar: Mock Registrar LLC
Expires in: 342 days
Status: clientTransferProhibited

How it works

The parse_whois function uses named regex patterns to capture key fields from the WHOIS text. The re.IGNORECASE flag makes matching case-insensitive. datetime.strptime converts the expiry date string into a datetime object for comparison with datetime.now(). The main block formats and prints the extracted information alongside the days remaining until expiration.

Common mistakes

  • Forgetting to use `re.search` vs `re.match`, which anchors matching to the start
  • Assuming date formats are consistent across all registrars
  • Not stripping whitespace from matched groups, leading to unclean values

Variations

  1. Use `re.compile` to precompile patterns for repeated calls
  2. Parse WHOIS data with `whois` library for real domain lookups

Real-world use cases

  • Automating domain portfolio monitoring to flag upcoming expirations for renewal.
  • Building an internal tool that audits registrars and domain statuses across a company.
  • Integrating WHOIS parsing into a script that validates domain ownership for certificate issuance.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.