Reputation: 16189
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 (e.g. 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.
Upvotes: 0
Views: 2044
Reputation: 2057
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:
6[4-9]
)[7-9]\d
)1[0-1]\d
)12[0-7]
)and
\d
)[1-9]\d
)1\d\d
)2[0-4]\d
)25[0-5]
)Upvotes: 3
Reputation: 6589
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']
Upvotes: 0