What are the Java regular expressions for matching IPv4 and IPv6 strings?

前端 未结 6 1828
抹茶落季
抹茶落季 2020-12-03 18:57

Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.

6条回答
  •  無奈伤痛
    2020-12-03 19:40

    Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed.

    The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.

    Code example:

    try {
        IPAddressString str = new IPAddressString("::1");
        IPAddress addr = str.toAddress();
    } catch(AddressStringException e) {
        //e.getMessage has validation error
    }
    

提交回复
热议问题