is IP address string by regex - Java java.util.regex

Java examples for java.util.regex:Match IP Address

Description

is IP address string by regex

Demo Code



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

public class AccessUtil {

    public static final String regex = "(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)";
    public static final Pattern pattern = Pattern.compile(regex);


    public static boolean testAccess(String[] ips, String ip) {
        String[] domains = ip.split("[\\.]");
        for (String s : ips) {
            String[] segment = s.split("[\\.]");
            boolean isMatched = true;
            for (int i = 0; i < 4; i++) {
                if (!matching(segment[i], domains[i])) {
                    isMatched = false;//  www  . ja v  a  2 s.c o  m
                    break;
                }
            }
            if (isMatched) {
                return true;
            }
        }
        return false;
    }

    public static boolean matching(String reg, String real) {
        if (reg.equals("*")) {
            return true;
        } else {
            return reg.equals(real);
        }
    }

    public static boolean isIP(String ip) {
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    public static void main(String[] args) {
        String[] reg = new String[] { "192.168.13.*" };
        String id = "192.168.14.64";
        System.out.println(testAccess(reg, id));
    }

}

Related Tutorials