Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for IP validation with range?

I need a regex pattern that validates IP addresses. This is easy enough to google for, but I there is a small catch. I need the last numbers to be able to accept a range. So the following input would validate.

XXX.XXX.XXX.X-Y

so something like 168.68.2.1-34

I have found patterns for normal IP addresses, but none for handling ranges.

like image 981
TheJediCowboy Avatar asked Apr 10 '26 01:04

TheJediCowboy


1 Answers

To accept a number between 0 and 255, I'd use (25[0-5]|2[0-4]\d|[0-1]?\d{1,2}). Calling the above expression A, a Regex for an IP Range would look like

A\.A\.A\.A-A

or

(A\.){3}A-A

If the range is optional, use (-A)? instead of -A.

This does not check if the start of the range is smaller than the end, but this cannot be done in Regex with reasonable effort.

like image 150
Jens Avatar answered Apr 12 '26 14:04

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!