views:

58

answers:

3

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.

+3  A: 

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).

Dean Harding
A minor (but important?) note here - if `(normal-ip-regex)` ends with `$`, the modified regex will not match anything.
Kobi
Isn't the range bounded? E.g., `123.123.123.123-99999` is probably not valid but would be matched by your regex.
Tim Pietzcker
+3  A: 

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.

Jens
+2  A: 

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).

Brenton Alker
Err.. looks like I misread the question, you actually want to take a range, not check against one. This is probably less helpful then.
Brenton Alker