简体   繁体   English

Python IP地址前缀匹配

[英]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: 我正在尝试将以下IP前缀范围10.[0-255], 192.168, 172.[16-31]与以下正则表达式匹配:

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. 但是,每次我尝试对测试用例10.10运行此命令时,都会引发错误。 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] . [01][0-9][0-9] But that's three digits, and 10 is two. 但这是三位数,而10是两位。 Consider [01]?[0-9]?[0-9] . 考虑[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. 不要以为这里真的需要正则表达式。

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

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