Module 1 · Python Foundations for Security Data · Lesson 3 of 9

Extract and validate IP addresses

Find candidate addresses in messy log text with re, then confirm each one with the ipaddress module.

In this lesson · about 20 minutes

  • Write a regular expression that finds IPv4-shaped text
  • Validate candidates with ipaddress and catch ValueError
  • Explain why a regex alone isn't validation

A regular expression (regex) describes a text pattern. This one finds four groups of one to three digits separated by dots:

r"\b(?:\d{1,3}\.){3}\d{1,3}\b"

It's a good candidate finder, but it also matches 999.12.3.4 and 10.0.0.300, which are impossible addresses. So the second step is validation with the standard library:

import ipaddress
try:
    ipaddress.ip_address("10.0.0.300")
except ValueError:
    print("not a real address")

Catch ValueError right next to the call that raises it, and only that error. Note that validation proves a string is a possible address, not that it was used as one: 2.4.10.7 in "build 2.4.10.7 deployed" is a valid IP but really a version number. Context still matters.

Candidates first

Exercise

Practice challenge 02: keep only real addresses

Write valid_ips(text) that finds candidates with the regex, validates each with ipaddress.ip_address, and returns a list of unique valid addresses (any order).

Check your understanding0 of 2 correct

Question 1

1.Why can a regex be insufficient for validating IPs?

Question 2

2.Which exception does ipaddress.ip_address raise for '10.0.0.300'?

Quiz score: 0 of 2

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. All data in this course is synthetic and uses documentation IP ranges. Never paste real authentication logs or credentials into online tools. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.