将ip地址转换成C段地址的UDF

将ip地址转换成C段地址的UDF,最重要的是判断IP地址的正则表达式。

package cn.cnnic.ops.Study;

import java.util.regex.Pattern;

import org.apache.hadoop.hive.ql.exec.UDF;

import cn.cnnic.ops.util.Constants;

/**
 * company: cnnic department: ops author: baoshan change client ip to C network
 * segment
 */

public class GetClientCSegment extends UDF {
    public static void main(String[] args) {
        String client = "210.72.32.1";
        GetClientCSegment gccs = new GetClientCSegment();
        System.out.println(gccs.evaluate(client));
    }

    public String evaluate(String client) {
        String ipCSegment = "";
        Pattern pattern = Pattern.compile(
                "^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]|[*])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]|[*])$");
        boolean flag = pattern.matcher(client).matches();
        String[] arr = client.split(Constants.DOT);
        if (flag) {
            ipCSegment = arr[0] + Constants.DOT_SIMPLE + arr[1] + Constants.DOT_SIMPLE + arr[2] + Constants.DOT_SIMPLE
                    + "0";
        } else {
            ipCSegment = client;
        }
        return ipCSegment;
    }
}
原文地址:https://www.cnblogs.com/zhzhang/p/5032700.html