IP validation with regular expression

I need to check the IP range, which is in the format from 000000000 to 255255255, without any separators between the three groups of numbers. Each of the three groups that make up the final IP should be 000 (yes, 0 supplemented) to 255.

Since this is my first stack entry, please be lenient if I don’t follow etiquette correctly.

+4
source share
5 answers
^([01]\d{2}|2[0-4]\d|25[0-5]){3}$ 

What happens in the following parts:

  • 000-199
  • 200-249
  • 250-255

If you decide you want 4 octets instead of 3, just change the last {3} to {4} . In addition, you should also know IPv6.

+8
source

I personally would not use regex for this. I think it’s easier to make sure that the string consists of 9 digits, divide the string into 3 groups of 3-digit numbers, and then check that each number is between 0 and 255, inclusive.

If you really insist on regex, you can use something like this:

 "([0-1][0-9][0-9]|2[0-4][0-9]|25[0-5]){3}" 

The expression contains an alternation of three terms: first matches 000-199 , second 200-249 , third 250-255 . {3} requires matching exactly three times.

+5
source

This is a fairly common question. Here is a nice page insert in regexps, which has this case as an example. It includes periods, but you can easily edit them.

+1
source

to match exclusively the actual use of the IP address

 (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]?)){3} 

instead

 ([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3} 

because many regex engines match the first possibility in the OR sequence

you can try your regex engine with: 10.48.0.200

0
source
 \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b 

I use this RegEx to find all ip in the code from my project

0
source

All Articles