java中的ip地址是否有效

时间:2013-05-06 15:29:59

标签: java regex validation ip-address port-number

我想使用正则表达式验证带或不带端口号的IP地址。我的输入字符串为IP:PORTIP。我只想要一个regex来验证IP:PORTIP

我的IP地址正则表达式是:

^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])$

有人可以告诉我如何在现有的正则表达式中添加可选端口号吗?

4 个答案:

答案 0 :(得分:1)

为什么这么复杂:谷歌为它:http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

你也试图在一个地方做太多事。使用正则表达式来获得它的好处,然后将其他智能用于正则表达式不适合的地方。在您的情况下,不要尝试验证正则表达式中的IP地址的值范围,但是在后处理中:

.... ^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:(\d{1,5}))?$

byte[] ip = new byte[4];
for (int i = 1; i <= 4; i++) {
    int bt = Integer.parseInt(matcher.group(i));
    if (bt < 0 || bt > 255) {
       throw new IllegalArgumentException("Byte value " + bt + " is not valid.");
    }
    ip[i-1] = (byte)bt;
}
integer port = 0;
if (matcher.group(6) != null) {
  port = Integer.parseInt(matcher.group(6));
}

答案 1 :(得分:1)

这很有效。

^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-‌​5])(?:[:]\d+)?$ 

答案 2 :(得分:1)

类解决方案{

public static void main(String[] args){

    Scanner in = new Scanner(System.in);

    while(in.hasNext()){

        String IP = in.next();

        System.out.println(IP.matches(new MyRegex().pattern));

    }



}

}

类MyRegex {

                                           String 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])$";

            }

private static final String IPADDRESS_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])$";

ı使用本网站的解决方案:

https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/

答案 3 :(得分:0)

使用尾随?标记可选部分,即将(:\\d+)添加到正则表达式的末尾。