Logo Wand.Tools

Regular Expression Generator

Intelligently generate and explain regular expressions, supporting various common pattern matching

Complete Tutorial on Matching IP Addresses with Regular Expressions (with Code Examples)

  # Complete Tutorial on Matching IP Addresses with Regular Expressions (with Code Examples)
  
  This tutorial provides a detailed guide on how to use regular expressions to match IPv4 and IPv6 addresses, suitable for scenarios like log analysis, data cleaning, and security filtering. It supports multi-language implementations and includes a detailed explanation of regex syntax and common examples to help you quickly master IP address matching techniques.
  
  ## 📌 Matching IPv4 Addresses with Regular Expressions
  
  An IPv4 address consists of four numbers between 0 and 255, separated by a dot `.`.
  
  ### ✅ IPv4 Regular Expression
  
  ```regex
  \b(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?:\.|$)){4}\b

🧪 Example Code (Python)

import re

pattern = r'\b(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?:\.|$)){4}\b'
text = "Valid IP address: 192.168.1.1, Invalid IP: 256.300.88.1"

matches = re.findall(pattern, text)
print("Matching results:", matches)

🌐 Matching IPv6 Addresses with Regular Expressions

An IPv6 address consists of 8 groups of hexadecimal numbers, separated by colons :, and can use the abbreviated form :: to represent consecutive zero fields.

✅ IPv6 Regular Expression

\b((?:(?:[0-9a-fA-F]{1,4}):){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\b

🧪 Example Code (Python)

import re

pattern = r'\b((?:(?:[0-9a-fA-F]{1,4}):){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|:(?::[0-9a-fA-F]{1,4}){1,7}|::)\b'
text = "Example IPv6 address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334, Abbreviated form ::1"

matches = re.findall(pattern, text)
print("Matching results:", matches)

🚀 Multi-language Support

JavaScript Example

const ipv4Regex = /\b(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?:\.|$)){4}\b/g;
const text = "IP addresses include 127.0.0.1 and 999.999.999.999";
const matches = text.match(ipv4Regex);
console.log("Matching results:", matches);

🔍 Regular Expression Key Points Summary

  • 25[0-5]: Matches numbers between 250 and 255
  • 2[0-4]\d: Matches 200 to 249
  • 1\d{2}: Matches 100 to 199
  • [1-9]?\d: Matches 0 to 99
  • (?:...): Non-capturing group
  • \b: Word boundary, ensures matching of a complete IP