Sunday, June 14, 2009

Regex for IP addresses

I was lazy and went looking for an example regex to match a dotted quad IP address and was a bit surprised at how wrong some of them are.

Here's one I'm using to validate input on a web form. I'm writing it here so I can find it again easy enough.

my $IPregex = '^([1-9]|[1-9]\d|[1]\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|[1]\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|[1]\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|[1]\d\d|2[0-4]\d|25[0-5])$';

This will match between 1.0.0.0 and 255.255.255.255, which suits my requirements.

No comments:

Post a Comment