Java Regex

  • + 0 comments

    import java.io.; import java.util.; import java.util.regex.*;

    public class Solution {

    public static void main(String[] args) {
      Scanner keyboard = new Scanner(System.in);
      String input;
      while(keyboard.hasNext()){
        input = keyboard.next();
        System.out.println(validate(input));
      }
      keyboard.close();
    }
    
    public static boolean validate(String input){
    
        String arr [] = input.split("[\\.]");
        if(arr.length != 4)
            return false;
    
        Pattern p = Pattern.compile("[0-9]+");
        for(String s : arr){
          if(s.length() > 3){
            return false;
          }
          Matcher m = p.matcher(s);
            if((m.matches()) == false)
                return false;
          Integer value = Integer.parseInt(s);
          if(value < 0 || value > 255)
            return false;
        }
        return true;
    }   
    

    }