Regex Example: IP Validator

Problem: Check wheather an ip is a valid ip or not

IP address has a predefined  form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255.

Solution:

Lets find the patern for A and same will be applied to other three as they follow same pattern.

Lets assume A is XYZ and value can range from 000–>255 or you can say that X can have possible value set of [0,1,2] , Y has [0-9] and Z has [0-9] but that depends on value of X prior

If X have value from [0,1] the Y and Z ahve same set of value which is [0-9].

[01]?dd

If X have value from [2] then Y have value from [0-4] and Z have value from [0-9].

2[0-4]d

If X have value from [2] && Y have value from [5] then Z value come from [0-5]

25[0-5]

Lets maerge all above create a pattern for A.

^( #check to first 
[01]? #either 0 or 1 occurence
dd
? #either 0 or 1 occurence
| #alternate
2
[0-4]
d
| #alternate
25[0-5]

^([01]?dd?|2[0-4]d|25[0-5])

Now same way apply this for B, C and D

Complete pattern is like this

^
([01]?dd?|2[0-4]d|25[0-5]).
([01]?dd?|2[0-4]d|25[0-5]).
([01]?dd?|2[0-4]d|25[0-5]).
([01]?dd?|2[0-4]d|25[0-5])
$

Thanks!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: