Photo-1 Photo-2 Photo-3 Photo-4 Photo-5 Photo-6



Full-time web developer. Part-time smart ass.

I'm Brent Collier.

After a year and a half as an engineer on Twitter's Trust & Safety team, I'm looking for my next gig. Contact me if you know of something interesting.


IP Address Regular Expressions

Posted on 09/26/2014

A regular expression for any ole ip address is pretty simple


It basically just looks for 1-3 digits and (period, 1-3 digits) x 3. So that'll match or or whatever. The problem though, is it will also match 999.999.999.999 and last time I checked, that's not a valid ip address.

For single digits, number ranges are super simple in regular expressions...

  • \d is 0..9
  • [0-9] is also 0..9
  • [2-7] is 2, 3, 4, 5, 6, or 7

It's when you get into multi-digit number ranges that things get hairy. For our ip address regex, no digit group should exceed 255. Heres the regex to match 0..255


And here it is within the ip address regex


That will match up to, but not What about zero-padded ip addresses? Well, first here's 000..255


And if we expand that into a fill ip address expression


Depending on how you need to use the regular expression, it may be helpful to bound it to the beginning/end of the string


You can see it in action here.

Here's a few others to match typical private ip ranges -

^10(?:\.(?:00\d|\d|0\d\d|\d\d|1\d\d|2[0-4]\d|25[0-5])){3}$ -

^172\.(?:\d|[1-2]\d|3[01])(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|\d\d|0\d\d|\d|00\d)){2}$ -