判断多个IP地址的合法性,这里采用了正则表达式的方法来判断(多个IP之间用 “,“ 分隔)

@SpringBootTest(classes = ServeApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class IpTest {


    /**
     * @Description: 判断多个IP地址的合法性,这里采用了正则表达式的方法来判断(多个IP之间用 "," 分隔)
     * @param: [ips  多个ip]
     * @return:boolean
     */
    public boolean ipsCheck(String ips) {
        boolean result = true;
        if (ips != null && !ips.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)$";
            String[] list = ips.split(",");
            for (String s : list) {
                boolean legitimate = s.matches(regex);
                if (!legitimate) {
                    result = false;
                    break;
                }
            }
        } else {
            result = false;
        }
        return result;
    }


    @Test
    public void ipTests() {
        String str = "8.8.8.8,4.4.4.4";
        System.out.println("str:" + this.ipsCheck(str));

        String str1 = "8.88.8,4.4.4.4";
        System.out.println("str1:" + this.ipsCheck(str1));

        String str2 = "8.8.8.84.4.4.4";
        System.out.println("str2:" + this.ipsCheck(str2));

        String str3 = "";
        System.out.println("str3:" + this.ipsCheck(str3));

        String str4 = null;
        System.out.println("str4:" + this.ipsCheck(str4));

        String str5 = " ";
        System.out.println("str5:" + this.ipsCheck(str5));

        if (this.ipsCheck(str1)){
            System.out.println("1");
        }else {
            System.out.println("2");
        }

    }

}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值