简体   繁体   中英

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

in my program i have to check against a IP address and decesion has to be made only if ip address's 4th octet is greater than XXX number. XXX = 120 for example.

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

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

i am tried something like 10\\.100\\.1\\.[2-9][3-9][9-9] but it is not correct.

Could someone help me out?

你可以尝试

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

To match numbers above 120 you can use

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

See this demo

Why not just split it, and check the integer at the end?

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)}"
}

You can also do this:

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] is what you want. The code will work with IPv6 too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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