How to Redact Emails and Phones Before Sending to an LLM in Python

This code uses regular expressions to replace email addresses and US phone numbers with [EMAIL] and [PHONE] placeholders before any LLM processing.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 15 views 0 copies

Python code

12 lines
Python 3.9+
import re

def redact_pii(text: str) -> str:
    # Replace email addresses with [EMAIL]
    text = re.sub(r'[\w.+-]+@[\w-]+\.[\w.-]+', '[EMAIL]', text)
    # Replace phone numbers (US format) with [PHONE]
    text = re.sub(r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}', '[PHONE]', text)
    return text

if __name__ == "__main__":
    sample = "Contact john.doe@example.com or 555-123-4567. Also try (415) 555-0199 and bob@domain.co."
    print(redact_pii(sample))

Output

stdout
Contact [EMAIL] or [PHONE]. Also try [PHONE] and [EMAIL].

How it works

The re.sub function searches the input string for patterns that match emails or US phone numbers and replaces them with safe placeholders. The email pattern covers common local parts and domain structures, while the phone pattern handles common formats like dashes, dots, spaces, and parentheses. This preprocessing step ensures sensitive PII is not accidentally sent to an external LLM API, protecting user privacy and helping with compliance.

Common mistakes

  • Overly broad patterns can catch non-PII data (like version numbers).
  • Not handling international phone numbers if needed.
  • Forgetting that redaction is not reversible — store original data separately if needed.

Variations

  1. Use a dedicated library like `scrubadub` for more thorough PII removal.
  2. Apply redaction only to fields you know contain PII rather than the whole text.

Real-world use cases

  • Sanitizing customer support tickets before sending them to an LLM for summarization.
  • Stripping emails from user-generated content before feeding it into a moderation model.
  • Filtering out contact details from logs before they are processed by an AI-powered log analyzer.

Sponsored

Run this sample

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

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.