简体   繁体   中英

Regex for range of IPv4 addresses

With an IPv4 address range like 169.254.0.0/16 or 192.168.0.0/16, it is straightforward to construct a regex for each, since once you exactly match the first 6 digits, you're done.

But what about matching any address in a looser reserved range such as

100.64.0.0 –
100.127.255.255

A regex beginning with 100\\. won't suffice, because there will be numbers outside of the 100.64 and 100.127 bounds (eg 100.65.0.0, 100.127.255.256) that will be erroneously matched. How best to capture a range such as this without having to explicitly define each and every valid subrange within each range? The language is Python.

For reference, a full list of reserved IP addresses and ranges can be found here .

Use of an IPv4 parsing library is preferred. If you insist in using regular expression,

re.search('^(100\\.(6[4-9]|[7-9]\\d|1[0-1]\\d|12[0-7])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){2})$', text)

You can see that I am searching separately for:

  • 64-69 ( 6[4-9] )
  • 70-99 ( [7-9]\\d )
  • 100-119 ( 1[0-1]\\d )
  • 120-127 ( 12[0-7] )

and

  • 0-9 ( \\d )
  • 10-99 ( [1-9]\\d )
  • 100-199 ( 1\\d\\d )
  • 200-249 ( 2[0-4]\\d )
  • 250-255 ( 25[0-5] )

This is one way to do it:

import re

print re.findall(r'\d+\.\S+\d', 'fdgsdfg 100.127.255.255 ggffgsdf 100.64.0.0 asdffsdf')

Output:

['100.127.255.255', '100.64.0.0']

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