Formatting IP:Port string to

前端 未结 6 638
遇见更好的自我
遇见更好的自我 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:12

    You can use pattern matcher in java to get the address and the port information and by the way you can validate the input string as well.

    Pattern pattern = Pattern.compile(REGEX_FOR_IPADDRESS_WITH_PORT);
    Matcher matcher = pattern.matcher("127.0.0.1:80");
    if (matcher.matches()) {
        System.out.printf("host = %s, port = %s%n", matcher.group(1), matcher.group(2));
    } else {
        System.out.println("Invalid Ip Address");
    }
    

    You can have multiple regular expression to validate V4 and V6 addresses. Hope this would help.

提交回复
热议问题