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 So I have developed my own:


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).