IP Address Regex Go Validator

Search...

⌘K

IP Address Regex Go Validator

Search...

⌘K


IP Address Regex Go Validator

IP Address Regex Go Validator

Validate IPv4 and IPv6 addresses accurately using the IP Address Regex Go Validator. Perfect for cleaning logs, validating user data, or building secure systems. Try this with our Go Regex Tester, or pair it with URL Validator, Email Validator, and GUID Validator for full input validation.

127.0.0.1
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Match information
Match 1: "127.0.0.1" at index 0
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

Introduction: What Is an IP Address Regex?

In Go, regular expressions (regex) offer a powerful way to validate patterns like IP addresses. IPs are fundamental in any network-based system—whether you’re storing user info, configuring firewalls, or building web applications.

IP addresses come in two types:

  • IPv4 (e.g., 192.168.1.1)

  • IPv6 (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334)


IP Address Regex Patterns

IPv4 Regex Pattern

^(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)){3}$

Supported Regex Flavors

These IPv4 regex patterns work across a wide range of modern regex engines, including those used in Go, Python, JavaScript, .NET, Java, Perl, Ruby, and PCRE. Whether you're integrating validation into backend code, scripts, or APIs, you can expect these expressions to behave consistently in most major development environments.


Explanation:

  • Validates 4 octets separated by dots.

  • Each octet ranges from 0 to 255.

  • Example match: 192.168.0.1


Additional Notes on IPv4 Validation

While you may come across simpler patterns like:

^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$

these match any four groups of 1–3 digits separated by dots but do not restrict the range to 0–255 for each octet. That means values like would pass, which aren't valid IP addresses.

The regex above is more accurate because it ensures each octet is within the valid IPv4 range. This pattern is supported across popular regex flavors, including .NET, Java, JavaScript, PCRE, Perl, Python, and Ruby.


Simple vs. Accurate IPv4 Regex Patterns


You may come across two types of regular expressions when validating IPv4 addresses: simple patterns and accurate patterns. It’s important to know the distinction, especially if you care about data quality.

Simple IPv4 Regex:
A basic regex might look like ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$. This checks for four groups of 1–3 digits separated by dots. It’s easy to write and understand, but it will happily match invalid addresses too—like 999.999.999.999 or even 256.100.100.100. In other words, it only checks the structure, not the validity of each octet.

Accurate IPv4 Regex:
A more precise pattern ensures each octet is between 0 and 255, catching common mistakes. For example:
^(25[0-5]2[0-4]\d1\d\d[1-9]?\d)(\.(25[0-5]2[0-4]\d1\d\d[1-9]?\d)){3}$
This looks intimidating, but it guarantees that inputs like 300.1.1.1 or 256.256.256.256 are rejected. It’s the way to go if your goal is bulletproof validation (firewall configs, user registration, and so on).

In summary:

  • Simple regex: Fast, but lets invalid addresses through.

  • Accurate regex: Slightly more complex, but ensures all addresses are truly valid IPv4.


Extracting IPv4 Addresses from Text with Regex


Need to pull IPv4 addresses out of raw logs or text blobs? Regular expressions make this task straightforward and efficient—no manual scanning required.

Here’s how you can isolate IPv4 addresses embedded in larger strings:

Quick Pattern for Basic Extraction

To match any sequence resembling an IPv4 address (regardless of its validity), use:

\b(?:[0-9]{1,3}\.){3}[0-9]
  • \b ensures whole-word matches, so partial numbers aren’t picked up.

  • The pattern checks for four sets of 1-3 digits separated by dots.

This version is simple and will pick up most IP-like sequences, even some that might fall outside the real range (like 999.999.999.999).

Stricter Pattern for Real Addresses

For stricter extraction that only returns syntactically valid IPv4 addresses (each octet between 0 and 255), use:

\b(?:(?:25[0-5]2[0-4][0-9]1\d\d[1-9]?\d)\.){3}
   (?:25[0-5]2[0-4][0-9]1\d\d[1-9]

  • This pattern checks each octet’s numerical limits, reducing false positives.

  • Works across major regex engines, including Go, Python, JavaScript, and PCRE.

Example:
Given Log: Failed attempt from 192.168.99.120 at noon, the stricter pattern extracts 192.168.99.120.

Whether you’re auditing logs, parsing CSV data, or building a tool for real-time monitoring, these patterns help you reliably pinpoint IPs in any chunk of text.


IPv6 Regex Pattern

^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$


Explanation:

  • Matches 8 groups of hexadecimal numbers separated by colons.

  • Each group has 1–4 hex digits.

  • Example match: 2001:0db8:85a3:0000:0000:8a2e:0370:7334


How to Validate IPs in Go Using Regex

Use Go’s built-in regexp package to compile the pattern and test strings:


package main

import (
    "fmt"
    "regexp"
)

func isValidIPv4(ip string) bool {
    ipv4Pattern := `^(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)){3}$`
    regex := regexp.MustCompile(ipv4Pattern)
    return regex.MatchString(ip)
}

func isValidIPv6(ip string) bool {
    ipv6Pattern := `^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$`
    regex := regexp.MustCompile(ipv6Pattern)
    return regex.MatchString(ip)
}

func main() {
    testIPs := []string{
        "192.168.1.1",                    // valid IPv4
        "256.300.88.1",                   // invalid IPv4
        "2001:0db8:85a3:0000:0000:8a2e:0370:7334", // valid IPv6
        "2001:db8::1",                    // invalid (compressed, unsupported here)
    }

    for _, ip := range testIPs {
        fmt.Printf("IP: %s | IPv4: %t | IPv6: %t\n", ip, isValidIPv4(ip), isValidIPv6(ip))
    }
}


Optional: Convert an IPv4 Address to a 32-bit Integer


Once you've validated your IPv4 address, you might need to convert it to a 32-bit integer—for example, for efficient storage, quick comparisons, or working with low-level networking APIs.

Here's how you can do it in Go:

import (
    "fmt"
    "strconv"
    "strings"
)

func ipv4ToInt(ip string) (uint32, error) {
    octets := strings.Split(ip, ".")
    if len(octets) != 4 {
        return 0, fmt.Errorf("invalid IPv4 address")
    }
    var result uint32
    for i := 0; i < 4; i++ {
        octet, err := strconv.Atoi(octets[i])
        if err != nil octet < 0 octet > 255 {
            return 0, fmt.Errorf("invalid octet in IPv4 address")
        }
        result = (result << 8) uint32(octet)
    }
    return result, nil

Usage example:

ip := "192.168.1.1"
ipInt, err := ipv4ToInt(ip)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Printf("IPv4 %s as uint32: %d", ip, ipInt

This function splits the IP by dots, parses each octet, and shifts bits into place—yielding a single 32-bit unsigned integer. Perfect for storing IPs compactly or using them as numeric keys in your service or cache.


Use Cases of IP Address Regex Validation

  • User IP Tracking: Validate IPs before storing them in logs or analytics tools.

  • Access Control: Only allow requests from whitelisted IP ranges.

  • Network Configuration: Automate validation of IPs during setup or provisioning.

  • Data Cleanup: Standardize datasets with malformed or corrupted IP records.


Pro Tips

  • Use IPv6 validation only when required, as many systems still rely primarily on IPv4.

  • Regex doesn’t validate reserved or local IPs (like 127.0.0.1 or ::1)—only format.

  • When working with compressed IPv6 formats (like ::1), consider using the net package for full parsing.

  • Use Go Regex Tester to fine-tune your IP patterns and test edge cases.


Combine with These Tools

Use the IP Address Regex Go Validator in workflows that also require:

Frequently asked questions

Can this validator distinguish between IPv4 and IPv6?×
Yes, it uses separate regex patterns for each format and matches them independently.
Does this handle CIDR notations like 192.168.1.0/24?+
Is the tool case-sensitive for IPv6?+
Does this support compressed IPv6 (e.g., ::1)?+
Can it detect reserved or private IP ranges?+