Regex to extract and redact IP addresses
user: can you give me some kind of formula that is an industry standard to parse out ip addresses of a txt document. it can be complete or partial obfuscation/redaction
assistant: Yep — the “industry standard” way to do this is:
1) **Use a regex to find *candidates*** (fast, works in grep/sed/ripgrep/etc.)
2) **Optionally validate candidates** (best practice) with a real IP parser (e.g., Python’s `ipaddress`) to avoid weird false-positives.
Below are solid, widely-used patterns and redaction variants.
---
## IPv4 extraction (strict 0–255 per octet)
**Regex (PCRE / most engines):**
```regex
\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b
```
**If you also want optional `:port`:**
```regex
\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b(?::\d{1,5})?
```
---
## IPv6 extraction (practical + common forms)
IPv6 regex can get *very* long if you try to perfectly cover every compressed form. The common industry approach is “good-enough extraction + validation”.
**Good extraction regex (covers most real-world IPv6 you’ll see, including `::` compression):**
```regex
\b(?:[0-9A-Fa-f]{1,4}:){1,7}[0-9A-Fa-f]{1,4}\b|\b(?:[0-9A-Fa-f]{1,4}:){1,7}:\b|\b:(?::[0-9A-Fa-f]{1,4}){1,7}\b
```
**If you also want bracketed IPv6 with optional port** (common in URLs/logs: `[2001:db8::1]:443`):
```regex
\[(?:[0-9A-Fa-f:]+)\](?::\d{1,5})?
```
(Then validate the inside of the brackets.)
---
## Redaction / obfuscation patterns
### A) Full redaction (replace any IPv4 with a token)
**Match (IPv4 strict)**:
```regex
\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b
```
**Replace with:**
```
[REDACTED_IP]
```
### B) Partial IPv4 redaction (keep /24, hide last octet)
**Match + capture first 3 octets:**
```regex
\b((?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b
```
**Replace with:**
```
$1.xxx
```
(Some tools use `\1` instead of `$1`.)
### C) Partial IPv6 redaction (keep prefix, hide the rest)
For IPv6, regex-only redaction gets messy because of compres…
user: Python
assistant: Here’s a solid “industry standard” Python approach: **regex for candidate matches + `ipaddress` for real validation**, with optional **redaction/obfuscation** (full token, partial, or deterministic hashing).
```python
#!/usr/bin/env python3
import re
import sys
import argparse
import ipaddress
import hashlib
from collections import Counter
# --- Candidate patterns (broad enough to catch real-world logs, then validated) ---
# [IPv6]:port (common in URLs/logs)
RE_V6_BRACKET = r"\[(?P<v6b>[0-9A-Fa-f:]{2,})\](?P<pb>:\d{1,5})?"
# IPv6 with embedded IPv4 (e.g., ::ffff:192.0.2.1) — no port here
RE_V6V4 = r"(?<![0-9A-Fa-f:])(?P<v6v4>(?:[0-9A-Fa-f]{0,4}:){1,6}\d{1,3}(?:\.\d{1,3}){3})(?![0-9A-Fa-f:])"
# IPv4 with optional :port
RE_V4 = r"(?P<v4>\b\d{1,3}(?:\.\d{1,3}){3}\b)(?P<p4>:\d{1,5})?"
# Practical IPv6 (most forms incl :: compression) — no port here
RE_V6 = (
r"(?<![0-9A-Fa-f:])"
r"(?P<v6>"
r"(?:[0-9A-Fa-f]{1,4}:){1,7}[0-9A-Fa-f]{1,4}|"
r"(?:[0-9A-Fa-f]{1,4}:){1,7}:|"
r":(?::[0-9A-Fa-f]{1,4}){1,7}"
r")"
r"(?![0-9A-Fa-f:])"
)
CANDIDATE_RE = re.compile(
f"{RE_V6_BRACKET}|{RE_V6V4}|{RE_V4}|{RE_V6}"
)
def _validate_ip(s: str):
try:
return ipaddress.ip_address(s)
except ValueError:
return None
def iter_ips_from_line(line: str, ipv4_only=False, ipv6_only=False):
for m in CANDIDATE_RE.finditer(line):
addr = None
if m.group("v6b"):
addr = m.group("v6b")
elif m.group("v6v4"):
addr = m.group("v6v4")
elif m.group("v4"):
addr = m.group("v4")
elif m.group("v6"):
addr = m.group("v6")
ip = _validate_ip(addr) if addr else None
if not ip:
continue
if ipv4_only and ip.version != 4:
continue
if ipv6_only and ip.version != 6:
continue
yield ip
def obfuscate_ip(ip, style: str, salt: str | None, ipv6_hextets: int):
s = ip.compressed
if style == "token"…
user: that's awesome! make an infographic for my blog my question of this subject matter and your solutions
Showing first 5 of 7 messages. View the full conversation at https://mcwai.org/ai-conversation/regex-to-extract-and-redact-ip-addresses