What are the Java regular expressions for matching IPv4 and IPv6 strings?

前端 未结 6 1752
抹茶落季
抹茶落季 2020-12-03 18:57

Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.

相关标签:
6条回答
  • 2020-12-03 19:24

    The regex allows the use of leading zeros in the IPv4 parts.

    Some Unix and Mac distros convert those segments into octals.

    I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d as an IPv4 segment.

    0 讨论(0)
  • 2020-12-03 19:35
    public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
    public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
    public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
    public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
    public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";
    

    Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.

    0 讨论(0)
  • 2020-12-03 19:40

    Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed.

    The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.

    Code example:

    try {
        IPAddressString str = new IPAddressString("::1");
        IPAddress addr = str.toAddress();
    } catch(AddressStringException e) {
        //e.getMessage has validation error
    }
    
    0 讨论(0)
  • 2020-12-03 19:50

    Another good option for processing IPs is to use Java's classes Inet4Address and Inet6Address, which can be useful in a number of ways, one of which is to determine the validity of the IP address.

    I know this doesn't answer the question directly, but just thought it's worth mentioning.

    0 讨论(0)
  • 2020-12-03 19:50

    Here's a regex to match IPv4 addresses:

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

    You'll need to escape the backslashes when you specify it as a string literal in Java:

    "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
    
    0 讨论(0)
  • 2020-12-03 19:50
    package com.capgemini.basics;
    
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.regex.PatternSyntaxException;
    
    public class Main {
        private static Pattern VALID_IPV4_PATTERN = null;
        private static Pattern VALID_IPV6_PATTERN1 = null;
        private static Pattern VALID_IPV6_PATTERN2 = null;
        private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
        private static final String ipv6Pattern1 = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
        private static final String ipv6Pattern2 = "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$";
    
    
        static {
            try {
                VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
                VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);
                VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);
            } catch (PatternSyntaxException e) {
                System.out.println("Neither");
            }
        }
    
        public static List<String> validateAddresses(List<String> ipAddress) {
            final List<String> validity= new ArrayList<String>();
            int len = ipAddress.size();
            for(int i=0; i<len; i++){
                Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));
                Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));
                Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));
                if (m1.matches()) {
                    validity.add("IPv4");
                }
                else if(m12.matches() || m22.matches()){
                    validity.add("IPv6");
                }
                else{
                    validity.add("Neither");
                }
            }
            return validity;
    
        }
    
        public static void main(String[] args)
        {
            final List<String> IPAddress = new ArrayList<String>();
            //Test Case 0
            /*IPAddress.add("121.18.19.20");
            IPAddress.add("0.12.12.34");
            IPAddress.add("121.234.12.12");
            IPAddress.add("23.45.12.56");
            IPAddress.add("0.1.2.3");*/
    
            //Test Case 1
            /*IPAddress.add("2001:0db8:0000:0000:0000:ff00:0042:8329");
            IPAddress.add("2001:0db8:0:0:0:ff00:42:8329");
            IPAddress.add("::1");
            IPAddress.add("2001:0db8::ff00:42:8329");
            IPAddress.add("0000:0000:0000:0000:0000:0000:0000:0001");*/
    
            //Test Case 2
            /*IPAddress.add("000.012.234.23");
            IPAddress.add("666.666.23.23");
            IPAddress.add(".213.123.23.32");
            IPAddress.add("23.45.22.32.");
            IPAddress.add("272:2624:235e:3bc2:c46d:682:5d46:638g");
            IPAddress.add("1:22:333:4444");*/
    
            final List<String> result = validateAddresses(IPAddress);
    
            for (int i=0; i<result.size(); i++)
                System.out.println(result.get(i)+" ");
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题