IP Address Regex Java Validator

Search...

⌘K

IP Address Regex Java Validator

Search...

⌘K


IP Address Regex Java Validator

The IP Address Regex Java Validator helps Java developers verify whether an input string is a valid IPv4 or IPv6 address. This is useful in backend validations, form inputs, firewalls, network utilities, and any application handling IP-related logic.


Try related Java tools:


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
Test your APIs today!

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

Regular Expression - Documentation

What is an IP Address?


An IP (Internet Protocol) Address is a unique identifier for devices on a network. It exists in two formats:


  • IPv4: 4 decimal octets (e.g. 192.168.0.1)

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


Correct validation ensures data routing and device identification works seamlessly.


IP Address Regex Patterns


IPv4 Regex Pattern:

^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.|$)){4}$


Explanation:

  • Ensures four blocks of numbers

  • Each block ranges from 0–255

  • Periods separate blocks


IPv6 Regex Pattern:

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


Explanation:

  • Ensures 8 groups of 1–4 hex digits

  • Groups are separated by colons


JavaScript Example: Validating IP Addresses


If you want to validate IP addresses in JavaScript, regular expressions are your best friend. Here’s a quick guide on how to check both IPv4 and IPv6 addresses using regex.

// Regular expressions for IPv4 and IPv6
const ipv4Pattern = /^((25[0-5]2[0-4]\d1\d\d[1-9]?\d)(\.$)){4}$/;
const ipv6Pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;

/**
 * Validates whether a given string is a valid IPv4 or IPv6 address.
 * @param {string} ip - IP address to validate.
 * @returns {string} - The type of IP address or 'Invalid IP'.
 */
function validateIPAddress(ip) {
  if (ipv4Pattern.test(ip)) {
    return "Valid IPv4 Address";
  }
  if (ipv6Pattern.test(ip)) {
    return "Valid IPv6 Address";
  }
  return "Invalid IP";
}

// Try it out with a few examples:
console.log(validateIPAddress("127.0.0.1"));                       // Valid IPv4 Address
console.log(validateIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); // Valid IPv6 Address
console.log(validateIPAddress("300.168.0.1"));                     // Invalid IP

This approach ensures that only properly formatted and valid ranges for both IPv4 and IPv6 pass your validation. Handy for frontend forms, backend validations, or quick command-line utilities.


Java Code Example (IPv4)


import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPv4Validator {
    public static void main(String[] args) {
        String ip = "192.168.1.1";
        String ipv4Regex = "^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.|$)){4}$";

        Pattern pattern = Pattern.compile(ipv4Regex);
        Matcher matcher = pattern.matcher(ip);

        if (matcher.matches()) {
            System.out.println("Valid IPv4 Address");
        } else {
            System.out.println("Invalid IPv4 Address");
        }
    }
}


Java Code Example (IPv6)


import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPv6Validator {
    public static void main(String[] args) {
        String ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
        String ipv6Regex = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$";

        Pattern pattern = Pattern.compile(ipv6Regex);
        Matcher matcher = pattern.matcher(ip);

        if (matcher.matches()) {
            System.out.println("Valid IPv6 Address");
        } else {
            System.out.println("Invalid IPv6 Address");
        }
    }
}


Sample Inputs


Valid IPv4:

  • 127.0.0.1

  • 192.168.100.100


Invalid IPv4:

  • 256.300.888.1

  • 192.168.1


Valid IPv6:

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

  • fe80::1ff:fe23:4567:890a


Invalid IPv6:

  • 2001:db8:85a3::8a2e:370g:7334 (invalid characters)

  • 1234:5678:90ab (too short)


Additional Examples:

Input

Output

203.120.223.13

Valid IPv4

000.12.234.23.23

Invalid IP

2F33:12a0:3Ea0:0302

Invalid IP

I.Am.not.an.ip

Invalid IP


These examples cover a range of typical cases you'll encounter—spanning valid and invalid IPv4 and IPv6 addresses, as well as edge cases like extra segments or non-numeric input. Use them to test your validation logic or as reference points for building robust IP address filters.


Performance Considerations


Time Complexity:
Validating an IP address using these regular expressions operates in linear time, or O(N), where N is the length of the input string. The pattern scans each character once, making it efficient even for longer addresses.

Space Complexity:
The space usage remains constant at O(1), as the regex engine doesn't require additional memory that scales with input size—just a fixed amount for tracking matches and capturing groups.

This makes regex-based IP validation both speedy and lightweight for everyday applications.


Use Cases

  • Login Attempts Tracking: Log IPs for failed or successful logins.

  • Geo IP Processing: Map user locations based on IPs.

  • API Whitelisting: Validate incoming IPs against allow-lists.

  • Form Validation: Accept only correctly formatted IPs in admin panels or dashboards.


Pro Tips

  • Use separate regex for IPv4 and IPv6 instead of a merged pattern to avoid confusion.

  • Clean input before validation (e.g., trim whitespace).

  • Don’t rely solely on regex—after format validation, use InetAddress.getByName() to confirm routable status.

  • Avoid trusting user-submitted IPs for security-sensitive operations like geo-location or access control.

  • Store IPs in consistent format (either full or shortened IPv6) in databases.

  • Use Java Regex Tester to test and fine-tune custom variations (e.g., CIDR ranges).


Combine with These Tools

Frequently asked questions

Does this validator support both IPv4 and IPv6?×
Yes, but you’ll need to use separate regex patterns for each.
Is this regex enough to check if an IP exists?+
Are leading zeros in IPv4 valid?+
Can I validate compressed IPv6?+
Should I store IPs as strings or numbers?+
Can I import Figma designs?+
Is it SEO-friendly?+
Can I collaborate with my team?+
Is hosting included?+
Can I export code?+
Is there a free plan?+
Can I use custom fonts?+

IP Address Regex Java Validator

Search...

⌘K

IP Address Regex Java Validator

Search...

⌘K


IP Address Regex Java Validator

IP Address Regex Java Validator

The IP Address Regex Java Validator helps Java developers verify whether an input string is a valid IPv4 or IPv6 address. This is useful in backend validations, form inputs, firewalls, network utilities, and any application handling IP-related logic.


Try related Java tools:


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
Test your APIs today!

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

Regular Expression - Documentation

What is an IP Address?


An IP (Internet Protocol) Address is a unique identifier for devices on a network. It exists in two formats:


  • IPv4: 4 decimal octets (e.g. 192.168.0.1)

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


Correct validation ensures data routing and device identification works seamlessly.


IP Address Regex Patterns


IPv4 Regex Pattern:

^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.|$)){4}$


Explanation:

  • Ensures four blocks of numbers

  • Each block ranges from 0–255

  • Periods separate blocks


IPv6 Regex Pattern:

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


Explanation:

  • Ensures 8 groups of 1–4 hex digits

  • Groups are separated by colons


JavaScript Example: Validating IP Addresses


If you want to validate IP addresses in JavaScript, regular expressions are your best friend. Here’s a quick guide on how to check both IPv4 and IPv6 addresses using regex.

// Regular expressions for IPv4 and IPv6
const ipv4Pattern = /^((25[0-5]2[0-4]\d1\d\d[1-9]?\d)(\.$)){4}$/;
const ipv6Pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;

/**
 * Validates whether a given string is a valid IPv4 or IPv6 address.
 * @param {string} ip - IP address to validate.
 * @returns {string} - The type of IP address or 'Invalid IP'.
 */
function validateIPAddress(ip) {
  if (ipv4Pattern.test(ip)) {
    return "Valid IPv4 Address";
  }
  if (ipv6Pattern.test(ip)) {
    return "Valid IPv6 Address";
  }
  return "Invalid IP";
}

// Try it out with a few examples:
console.log(validateIPAddress("127.0.0.1"));                       // Valid IPv4 Address
console.log(validateIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); // Valid IPv6 Address
console.log(validateIPAddress("300.168.0.1"));                     // Invalid IP

This approach ensures that only properly formatted and valid ranges for both IPv4 and IPv6 pass your validation. Handy for frontend forms, backend validations, or quick command-line utilities.


Java Code Example (IPv4)


import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPv4Validator {
    public static void main(String[] args) {
        String ip = "192.168.1.1";
        String ipv4Regex = "^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.|$)){4}$";

        Pattern pattern = Pattern.compile(ipv4Regex);
        Matcher matcher = pattern.matcher(ip);

        if (matcher.matches()) {
            System.out.println("Valid IPv4 Address");
        } else {
            System.out.println("Invalid IPv4 Address");
        }
    }
}


Java Code Example (IPv6)


import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPv6Validator {
    public static void main(String[] args) {
        String ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
        String ipv6Regex = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$";

        Pattern pattern = Pattern.compile(ipv6Regex);
        Matcher matcher = pattern.matcher(ip);

        if (matcher.matches()) {
            System.out.println("Valid IPv6 Address");
        } else {
            System.out.println("Invalid IPv6 Address");
        }
    }
}


Sample Inputs


Valid IPv4:

  • 127.0.0.1

  • 192.168.100.100


Invalid IPv4:

  • 256.300.888.1

  • 192.168.1


Valid IPv6:

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

  • fe80::1ff:fe23:4567:890a


Invalid IPv6:

  • 2001:db8:85a3::8a2e:370g:7334 (invalid characters)

  • 1234:5678:90ab (too short)


Additional Examples:

Input

Output

203.120.223.13

Valid IPv4

000.12.234.23.23

Invalid IP

2F33:12a0:3Ea0:0302

Invalid IP

I.Am.not.an.ip

Invalid IP


These examples cover a range of typical cases you'll encounter—spanning valid and invalid IPv4 and IPv6 addresses, as well as edge cases like extra segments or non-numeric input. Use them to test your validation logic or as reference points for building robust IP address filters.


Performance Considerations


Time Complexity:
Validating an IP address using these regular expressions operates in linear time, or O(N), where N is the length of the input string. The pattern scans each character once, making it efficient even for longer addresses.

Space Complexity:
The space usage remains constant at O(1), as the regex engine doesn't require additional memory that scales with input size—just a fixed amount for tracking matches and capturing groups.

This makes regex-based IP validation both speedy and lightweight for everyday applications.


Use Cases

  • Login Attempts Tracking: Log IPs for failed or successful logins.

  • Geo IP Processing: Map user locations based on IPs.

  • API Whitelisting: Validate incoming IPs against allow-lists.

  • Form Validation: Accept only correctly formatted IPs in admin panels or dashboards.


Pro Tips

  • Use separate regex for IPv4 and IPv6 instead of a merged pattern to avoid confusion.

  • Clean input before validation (e.g., trim whitespace).

  • Don’t rely solely on regex—after format validation, use InetAddress.getByName() to confirm routable status.

  • Avoid trusting user-submitted IPs for security-sensitive operations like geo-location or access control.

  • Store IPs in consistent format (either full or shortened IPv6) in databases.

  • Use Java Regex Tester to test and fine-tune custom variations (e.g., CIDR ranges).


Combine with These Tools

Frequently asked questions

Does this validator support both IPv4 and IPv6?×
Yes, but you’ll need to use separate regex patterns for each.
Is this regex enough to check if an IP exists?+
Are leading zeros in IPv4 valid?+
Can I validate compressed IPv6?+
Should I store IPs as strings or numbers?+