正则表达式验证IP地址的合法性

package test;

public class Regex {
    public static void main(String[] args) {
        System.out.println(ipCheck("192.168.12.231"));
    }

    /**
     * 验证ip是否合法
     *
     * @param text
     *            ip地址
     * @return 验证信息
     */
    public static String ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return text + "\n是一个合法的IP地址!";
            } else {
                // 返回判断信息
                return text + "\n不是一个合法的IP地址!";
            }
        }
        // 返回判断信息
        return "请输入要验证的IP地址!";
    }
}

posted @ 2017-02-23 11:57  one_person  阅读(7979)  评论(0编辑  收藏  举报