Java Regular Expression match IP address

Description

Java Regular Expression match IP address


import java.util.regex.Pattern;

public class Main{
    public static void main(String[] argv) throws Exception{
        String s = "123.123.123.123";
        System.out.println(checkIP(s));
    }/*w w  w  .j ava  2s  . co m*/
    public static boolean checkIP(String s) {
        Pattern pattern = Pattern.compile("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]"
                + "|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$");
        return pattern.matcher(s).matches();
    }
}

import java.util.regex.Pattern;

public class Main {
  public static void main(String[] argv) throws Exception {
    CharSequence sequence = "";
    System.out.println(isIpv4(sequence));
  }// ww  w .j  av  a  2 s.  c o  m

  public static boolean isIpv4(CharSequence sequence) {
    String pattern = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
    return matcher(pattern, sequence);
  }

  public static boolean matcher(String pattern, CharSequence sequence) {
    if (isEmpty(pattern) || isEmpty(sequence))
      return false;
    Pattern compile = Pattern.compile(pattern);
    if (compile == null)
      return false;
    return compile.matcher(sequence).matches();
  }

  public static boolean isEmpty(CharSequence sequence) {
    return sequence == null || sequence.length() == 0;
  }
}



PreviousNext

Related