[javascript] javascript regular expression to check for IP addresses

I have several ip addresses like:

  1. 115.42.150.37
  2. 115.42.150.38
  3. 115.42.150.50

What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.* (I will be able to search for all 3 ip addresses)

What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ but it can't seems to work well.

Thanks.

This question is related to javascript regex string string-matching

The answer is


Regular expression for the IP address format:

/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;

Simple Method

const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}

\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b

matches 0.0.0.0 through 999.999.999.999 use if you know the seachdata does not contain invalid IP addresses

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

use to match IP numbers with accurracy - each of the 4 numbers is stored into it's own capturing group, so you can access them later


May be late but, someone could try:

Example of VALID IP address

115.42.150.37
192.168.0.1
110.234.52.124

Example of INVALID IP address

210.110 – must have 4 octets
255 – must have 4 octets
y.y.y.y – only digits are allowed
255.0.0.y – only digits are allowed
666.10.10.20 – octet number must be between [0-255]
4444.11.11.11 – octet number must be between [0-255]
33.3333.33.3 – octet number must be between [0-255]

JavaScript code to validate an IP address

function ValidateIPaddress(ipaddress) {  
  if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {  
    return (true)  
  }  
  alert("You have entered an invalid IP address!")  
  return (false)  
}  

Try this one, it's a shorter version:

^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$

Explained:

^ start of string
  (?!0)         Assume IP cannot start with 0
  (?!.*\.$)     Make sure string does not end with a dot
  (
    (
    1?\d?\d|   A single digit, two digits, or 100-199
    25[0-5]|   The numbers 250-255
    2[0-4]\d   The numbers 200-249
    )
  \.|$ the number must be followed by either a dot or end-of-string - to match the last number
  ){4}         Expect exactly four of these
$ end of string

Unit test for a browser's console:

var rx=/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
var valid=['1.2.3.4','11.11.11.11','123.123.123.123','255.250.249.0','1.12.123.255','127.0.0.1','1.0.0.0'];
var invalid=['0.1.1.1','01.1.1.1','012.1.1.1','1.2.3.4.','1.2.3\n4','1.2.3.4\n','259.0.0.1','123.','1.2.3.4.5','.1.2.3.4','1,2,3,4','1.2.333.4','1.299.3.4'];
valid.forEach(function(s){if (!rx.test(s))console.log('bad valid: '+s);});
invalid.forEach(function(s){if (rx.test(s)) console.log('bad invalid: '+s);});

And instead of

{1-3}

you should put

{1,3}

The answers over allow leading zeros in Ip address, and that it is not correct. For example ("123.045.067.089"should return false).

The correct way to do it like that.

 function isValidIP(ipaddress) {  
if (/^(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)$/.test(ipaddress)) {  
  return (true)  
}   
return (false) } 

This function will not allow zero to lead IP addresses.


This is what I did and it's fast and works perfectly:

function isIPv4Address(inputString) {
    let regex = new RegExp(/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/);
    if(regex.test(inputString)){
        let arInput = inputString.split(".")
        for(let i of arInput){
            if(i.length > 1 && i.charAt(0) === '0')
                return false;
            else{
                if(parseInt(i) < 0 || parseInt(i) >=256)
                   return false;
            }
        }
    }
    else
        return false;
    return true;
}

Explanation: First, with the regex check that the IP format is correct. Although, the regex won't check any value ranges.

I mean, if you can use Javascript to manage regex, why not use it?. So, instead of using a crazy regex, use Regex only for checking that the format is fine and then check that each value in the octet is in the correct value range (0 to 255). Hope this helps anybody else. Peace.


If you want something more readable than regex for ipv4 in modern browsers you can go with

function checkIsIPV4(entry) {
  var blocks = entry.split(".");
  if(blocks.length === 4) {
    return blocks.every(function(block) {
      return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
    });
  }
  return false;
}

A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$

Example

_x000D_
_x000D_
const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value) ? true : false);_x000D_
_x000D_
_x000D_
// valid_x000D_
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));_x000D_
console.log("isValidIp('110.234.52.124' ? ", isValidIp('110.234.52.124'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));_x000D_
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));_x000D_
_x000D_
// Invalid_x000D_
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));_x000D_
console.log("isValidIp('255') ? ", isValidIp('255'));_x000D_
console.log("isValidIp('y.y.y.y' ? ", isValidIp('y.y.y.y'));_x000D_
console.log(" isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));_x000D_
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));_x000D_
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));_x000D_
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
_x000D_
_x000D_
_x000D_


If you wrtie the proper code you need only this very simple regular expression: /\d{1,3}/

function isIP(ip) {
    let arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    let re = /\d{1,3}/;
    for (let oct of arrIp) {
        if (oct.match(re) === null) return "Invalid IP"
        if (Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}

But actually you get even simpler code by not using any regular expression at all:

function isIp(ip) {
    var arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    for (let oct of arrIp) {
        if ( isNaN(oct) || Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}

/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/

Full credit to oriadam. I would have commented below his/her answer to suggest the double zero change I made, but I do not have enough reputation here yet...

change:


Throwing in a late contribution:

^(?!\.)((^|\.)([1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d))){4}$

Of the answers I checked, they're either longer or incomplete in their verification. Longer, in my experience, means harder to overlook and therefore more prone to be erroneous. And I like to avoid repeating similar patters, for the same reason.

The main part is, of course, the test for a number - 0 to 255, but also making sure it doesn't allow initial zeroes (except for when it's a single one):

[1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d)

Three alternations - one for sub 100: [1-9]?\d, one for 100-199: 1\d\d and finally 200-255: 2(5[0-5]|[0-4]\d).

This is preceded by a test for start of line or a dot ., and this whole expression is tested for 4 times by the appended {4}.

This complete test for four byte representations is started by testing for start of line followed by a negative look ahead to avoid addresses starting with a .: ^(?!\.), and ended with a test for end of line ($).

See some samples here at regex101.


Don't write your own regex or copy paste! You probably won't cover all edge ceses (IPv6, but also octal IPs, etc). Use the is-ip package from npm:

var isIp = require('is-ip');

isIp('192.168.0.1');

isIp('1:2:3:4:5:6:7:8');

Will return a Boolean.

Downvoters: care to explain why using an actively maintained library is better than copy pasting from a website?


Always looking for variations, seemed to be a repetitive task so how about using forEach!

function checkIP(ip) {
  //assume IP is valid to start, once false is found, always false
  var test = true;

  //uses forEach method to test each block of IPv4 address
  ip.split('.').forEach(validateIP4);

  if (!test) 
    alert("Invalid IP4 format\n"+ip) 
  else 
    alert("IP4 format correct\n"+ip);

  function validateIP4(num, index, arr) {
    //returns NaN if not an Int
    item = parseInt(num, 10);
    //test validates Int, 0-255 range and 4 bytes of address
    // && test; at end required because this function called for each block
    test = !isNaN(item) && !isNaN(num) && item >=0 && item < 256 && arr.length==4 && test;
  }
}

it is maybe better:

function checkIP(ip) {
    var x = ip.split("."), x1, x2, x3, x4;

    if (x.length == 4) {
        x1 = parseInt(x[0], 10);
        x2 = parseInt(x[1], 10);
        x3 = parseInt(x[2], 10);
        x4 = parseInt(x[3], 10);

        if (isNaN(x1) || isNaN(x2) || isNaN(x3) || isNaN(x4)) {
            return false;
        }

        if ((x1 >= 0 && x1 <= 255) && (x2 >= 0 && x2 <= 255) && (x3 >= 0 && x3 <= 255) && (x4 >= 0 && x4 <= 255)) {
            return true;
        }
    }
    return false;
}    

A less stringent when testing the type not the validity. For example when sorting columns use this check to see which sort to use.

export const isIpAddress = (ipAddress) => 
    /^((\d){1,3}\.){3}(\d){1,3}$/.test(ipAddress)

When checking for validity use this test. An even more stringent test checking that the IP 8-bit numbers are in the range 0-255:

export const isValidIpAddress = (ipAddress) => 
    /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)

If you are using nodejs try:

require('net').isIP('10.0.0.1')

doc net.isIP()


Below Solution doesn't accept Padding Zeros

Here is the cleanest way to validate an IP Address, Let's break it down:

Fact: a valid IP Address is has 4 octets, each octets can be a number between 0 - 255

Breakdown of Regex that matches any value between 0 - 255

  • 25[0-5] matches 250 - 255
  • 2[0-4][0-9] matches 200 - 249
  • 1[0-9][0-9] matches 100 - 199
  • [1-9][0-9]? matches 1 - 99
  • 0 matches 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.

function isValidIP(str) {
  const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
  const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`);
  return regex.test(str);
}

Try this one.. Source from here.

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to string-matching

Filter multiple values on a string column in dplyr PowerShell and the -contains operator Check if string matches pattern How to check if matching text is found in a string in Lua? Check whether a string contains a substring Perl - If string contains text? How to search a specific value in all tables (PostgreSQL)? javascript regular expression to check for IP addresses Regular Expression Match to test for a valid year How do I check if a string contains a specific word?