Blog

5Sep
2003
RegEx: Match and Validate an IP Address

I am a night person, the wee hours are when I get most inspired. Here's a regular expression I wrote last night, um, make that this morning. It matches an IP address, and also ensures that the values are within the allowed range (0-255).

view plain print about
1(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))

Comments (8)



  • tc

    Ben,

    One added feature for CF, I would like to see is a MATCHES function (using Regular Expressions). In CFMX, I go around the server and use Java's built-in matches method, but one has to make sure they cast the variable to a string object (numbers are often cast to Integers or Number ojbects instead of strings). Where it comes in handy is when I am attempting to validate input on the server side (e.g., validate a phone number, SSN, or other non-standard variable types, like your IP address expression).

    Thanks

    #1Posted by tc | Sep 12, 2003, 06:58 PM
  • Sutton

    Nice RE!!!

    #2Posted by Sutton | Sep 29, 2003, 07:51 PM
  • dirt

    IP addresses cannot have zero by itself in the first octet. I'd give you a corrected RE if I knew it. Still looking...

    #3Posted by dirt | Dec 22, 2003, 07:53 PM
  • Brad Younie

    Although it's great, all in all, I did find one hole in the RE. It seems to let me enter numbers of 4 digits and higher. That is, it will not let me enter 256, but it will let me enter 10000. I wish I knew what to add to fix it, but I can't think of it right now.

    I thought I'd let you know.

    #4Posted by Brad Younie | Mar 29, 2004, 01:51 PM
  • sprion

    perhaps this is better:

    (2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)

    #5Posted by sprion | Jan 15, 2005, 06:45 AM
  • sprion

    (((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))

    my mistake.

    #6Posted by sprion | Jan 15, 2005, 06:47 AM
  • duke

    nerd

    #7Posted by duke | Feb 6, 2005, 10:49 AM
  • Bruce

    duke - What was that about? :p

    sprion - I messed up similarly my first time too :)

    Bruce Byford
    http://www.powernetshop.at

    #8Posted by Bruce | Jun 11, 2008, 06:47 AM