Regular expression for IP series?

I'm trying to check if there is an input text:

(IP| IP1, IP2 | IP1, IP2, IP3) and so on .....

      

for example 172.25.1.4

or 172.25.1.4, 172.25.1.5

or
172.25.1.4, 172.25.1.6, 3.3.3.3

etc. accepted.

and the space between IPS is not required either: is 172.25.1.4,172.25.1.5

accepted

I don't know what to use as a template:

var pattern = theCorrectPattern

if (!pattern.test(id1) && id1.value!="") {

    document.getElementById("id").innerHTML="<p style='color:red'>not correct</p>";

}

else

{
    document.getElementById("id").innerHTML="<p></p>";

}

      

+3


source to share


1 answer


Let's build this to pieces. First, we need a regular expression for a single octet (one of the four parts of the IP). The number can go from 0 to 255. How can we accomplish this with a regular expression?

For the 0-199 case, we can have a simple regex that allows an optional 0 or 1, followed by at least one but no more than two digits in the range 0-9:

/[01]?[0-9]{1,2}/

      

Now we need to process case 200-255. It's a little tricky; for example, 249 is valid, but 259 is not. So we have another pattern that requires 2, followed by one digit in the range 0-4, followed by one digit in the range 0-9. This handles case 200-249:

/2[0-4][0-9]/

      

Finally, we need a template to handle the final 250-255 file, which should be fairly obvious:

/25[0-5]/

      

Let's have them concatenated into one regular expression that we can use for our octet:

/([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))/
  ^ 0-199 case    ^ 200s
                     ^ 200-249 ^ 250-255

      

A bit cumbersome perhaps, but it works. Let's use this opportunity for use in our future templates.



var octetPattern = "([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))";

      

We now need a template that will handle four of them, separated by dots. We do this by matching one octet and then matching 3 from (period, octet).

var ipPattern = octetPattern + "(\\." + octetPattern + "){3}";

      

Almost there. Our final pattern matches an IP followed by zero or more (comma, optional spaces, IP):

var ipGroupPattern = ipPattern + "(, *" + ipPattern + ")*";

      

We will now construct a RegExp object from it using anchor characters. (Without them, the pattern will match any text containing an IP group; we only want to match if the full text matches.)

var pattern = new RegExp("^" + ipGroupPattern + "$");

      

All this leads to this lovely mess:

/^([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))(\.([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))){3}(, *([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))(\.([01]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))){3})*$/

      

( See how it works .)

+4


source







All Articles