码迷,mamicode.com
首页 > 编程语言 > 详细

java使用正则表达式验证IP V4、 IP V6

时间:2015-04-22 11:34:04      阅读:394      评论:0      收藏:0      [点我收藏+]

标签:

package cn.outofmemory.snippets.core;

import java.util.regex.Pattern;

/**
 * A collection of utilities relating to InetAddresses.
 */
public class InetAddressUtils {

    public static void main(String[] args){
        String addr="192.168.1.2";

        System.out.println(isIPv4Address(addr));

    }

    private InetAddressUtils() {
    }

    private static final Pattern IPV4_PATTERN = 
        Pattern.compile(
                "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

    private static final Pattern IPV6_STD_PATTERN = 
        Pattern.compile(
                "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");

    private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = 
        Pattern.compile(
                "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

    public static boolean isIPv4Address(final String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6StdAddress(final String input) {
        return IPV6_STD_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6HexCompressedAddress(final String input) {
        return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6Address(final String input) {
        return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); 
    }

}

 本文转自:http://outofmemory.cn/code-snippet/1197/java-usage-regular-expression-yanzheng-IP-v4-IP-v6-address

java使用正则表达式验证IP V4、 IP V6

标签:

原文地址:http://www.cnblogs.com/Rozdy/p/4446698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!