Formatting IP:Port string to

前端 未结 6 641
遇见更好的自我
遇见更好的自我 2021-01-23 07:13

I\'m trying to make a little chat program for experimentation, but seeing as I\'m not the best Java programmer, I don\'t know how to separate a port from an IP where they are bo

6条回答
  •  太阳男子
    2021-01-23 08:05

    to validate IP:PORT format you may try this:

    public class Validator {
    
        private static final String IP_PORT_PATTERN =
                "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" +
                        "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$";
    
        private static final Pattern PATTERN;
    
        static {
            PATTERN = Pattern.compile(IP_PORT_PATTERN);
        }
    
        public static boolean validate(final String s) {
            return PATTERN.matcher(s).matches();
        }
    
    }
    

    thanks to frb and mkyong :)

    and to separate ip and port :

    public static void main(String args[]) {
        String s = "127.0.0.1:8080";
        if (validate(s)) {
            String ip = s.substring(0, s.indexOf(':'));
            int port = Integer.parseInt(s.substring(s.indexOf(':') + 1));
            System.out.println(ip);
            System.out.println(port);
        } else {
            System.out.println("invalid format");
        }
    }
    

提交回复
热议问题