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 hand开发者_如何学Cling ranges.
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.
Well then, it'll just be:
(normal-ip-regex)-[0-9]+
If you need anything more complicated than that, then I'd say your best bet is to actually parse the numbers out and validate them that way (for example, if you want to actually make sure "X" is less than "Y" then there's no way to do that with a regular expression).
A "better" way to validate IP addresses is to convert them into an integer. Remembering that the dot notation is just to make them easier for humans to read.
I don't know what language you are using, but most will have something like the inet_aton
function to convert from dot notation to an integer (which will implicitly check the format is correct).
Once you have the address as an integer, you can check it is within your valid range the same way you check any other integer (< and >, most likely).
精彩评论