Regex: checking user ipv4 input

Regex: checking user ipv4 input

By d-erf | Devtips | 19 Oct 2020


Hello all!

 

Ok, it's regex time!

 

Further than just ipv4 check, it uses common regex knowledge and tips.

 

I will present you in a coming article tools to help creating, testing and coding in regex world.

 

For now, here are 4 javascript regexes to check ipv4 user input:

 

 

ip without mask:

example: 10.0.0.1

^(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])$

 

list of ips without mask:

example: 254.0.0.1,10.0.0.24

^(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])+(?:\,(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]))*$

 

 

with cidr suffix:

example: 10.0.0.1/24

 

^(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\/(?:[1-9][0-9]|[1-9])$

 

 

cidr suffixed ip list:

example: 254.0.0.1/32,10.0.3.2/23

 

^(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\/(?:[1-9][0-9]|[1-9])+(?:\,(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\/(?:[1-9][0-9]|[1-9]))*$

 

 

 

Ok, that's done! Enjoy!

 

 

Feel free to tip me, it will encourage me to publish more interesting and useful content!

 

Have you read my other posts, click here!

 

Don't you know publish0x? It's an alternative and innovative free blogging platform paying in crypto just for viewing (with their bat coins pool) and for authoring, clic here to try

 

Follow me on publish0x, and on twitter!

 

See you all!



Devtips
Devtips

Dev tips and tricks

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.