2006-11-16

Regular Expression To Match IPv4 Addresses

I needed a regex pattern to match IPv4 addresses today. I thought that this is quite common thing and it will be easy to find one on the Net. I have found a lot of them indeed. Unfortunately no one was good enough. Most of them was too simple and could match a string which is not IPv4 address. On the other hand, those more specific didn't match some fully legal IPv4 addresses (for example the one from regexlib.com). So I have developed my own:
((2[0-5]{2}|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(2[0-5]{2}|2[0-4]\d|1\d{2}|[1-9]\d|\d)
(/(3[012]|[12]\d|\d))?
This pattern matches all (I hope) IPv4 addresses in dot-decimal notation (first line) and network blocks in CIDR notation (when you join second line).