繁体   English   中英

regex检查IP地址的第四个八位字节是否大于XXX

[英]regex to check if IP address's 4th octet is greather than XXX

在我的程序中,我必须检查IP地址,并且仅当ip地址的第四个八位字节大于XXX数字时才需要进行决策。 例如,XXX = 120。

       for example: 
       IP1 = 10.100.1.121
       IP2 = 10.100.1.119
       IP3 = 10.100.1.122

if($IP =~ /10\.100\.1\.**<120**/)

我尝试过类似10\\.100\\.1\\.[2-9][3-9][9-9]但这是不正确的。

有人可以帮我吗?

你可以尝试

10\.100\.1\.(12[1-9]|1[3-9][0-9]|[2-9][0-9][0-9])

要匹配120以上的数字,您可以使用

/\b10\.100\.1\.(?:12[1-9]|1[3-9][0-9]|2[0-4][0-9]|25[0-5])\b/

这个演示

为什么不将其拆分,然后在末尾检查整数?

def ips = ['10.100.1.121',
           '10.10.0.1',
           '10.100.1.119',
           '10.100.1.122']

def lastOctetGreaterThan(String ip, int number) {
    Integer.valueOf(ip.split(/\./).last()) > number
}

ips.each { ip ->
    println "$ip => ${lastOctetGreaterThan(ip, 120)}"
}

您也可以这样做:

import java.net.InetAddress

def octet = InetAddress.getByName(ip)         // x.x.x.x -> InetAddress
                       .getAddress()          // InetAddress -> byte[]
                       .collect { it & 0xff } // positive numbers only

octet[3]是您想要的。 该代码也适用于IPv6。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM