AdobeStock_455007340

RegEx: Match and Validate an IP Address

Home » 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).
(((d{1,2})|(1d{2})|(2[0-4]d)|(25[0-5])).){3}((d{1,2})|(1d{2})|(2[0-4]d)|(25[0-5]))

8 responses to “RegEx: Match and Validate an IP Address”

  1. tc Avatar
    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

  2. Sutton Avatar
    Sutton

    Nice RE!!!

  3. dirt Avatar
    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…

  4. Brad Younie Avatar
    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.

  5. sprion Avatar
    sprion

    perhaps this is better:
    (2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)

  6. sprion Avatar
    sprion

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

  7. duke Avatar
    duke

    nerd

  8. Bruce Avatar
    Bruce

    duke – What was that about? :p
    sprion – I messed up similarly my first time too 🙂
    Bruce Byford
    http://www.powernetshop.at

Leave a Reply