简体   繁体   中英

Python IP address prefix matching

I am trying to match the following ranges of IP prefixes 10.[0-255], 192.168, 172.[16-31] with the following regex statements:

if not ((re.match("^10\.([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$", event["vpcprefix"]))
        or (event["vpcprefix"] == "192.168")
        or (re.match("^172\.(1[6-9]|2[0-9]|3[0-1])$", event["vpcprefix"]))):
            #throw error, not matched

However, every time I try to run this against the test case 10.10 it throws an error. I'm not sure why, I can't find any errors in my statements.

You have three patterns. Clearly only the first has any chance of being true, and within that the closest option between the | 's is [01][0-9][0-9] . But that's three digits, and 10 is two. Consider [01]?[0-9]?[0-9] .

How about:

if not ((event["vpcprefix"].split('.')[0] == '10')
        or (event["vpcprefix"] == "192.168")
        or (event["vpcprefix"].split('.')[0] == '172')):
            #do stuff

don't think you really need the regex here.

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