Q:

What are the java regular expressions for matching IPv4 and IPv6 string ?

0

What are the java regular expressions for matching IPv4 and IPv6 string ?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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>();
        final List<String> result = validateAddresses(IPAddress);
        for (int i=0; i<result.size(); i++)
            System.out.println(result.get(i)+" ");
    }
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now