kRicha kRicha - 5 days ago 5
PHP Question

regex for validating ip-range from ip-list

I have regex for validating list of 50 ips comma-separated:

^(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:,? ?)){1,50}$


list example:

10.10.10.1,127.0.0.1


now i need to support list, like this:

10.10.10.1,127.0.0.1-127.0.0.125


i try, to use subpatterns, but nothing happened

can somebody provide regex example for validating this string:

127.0.0.1-127.0.0.125

Answer

You may use 2 things here: use the negated character class to match either , or -, and use a subrouting call to make sure your pattern stays of a reasonable size and the string cannot start with , or -:

^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:[,-](?1)){0,49}$

See the regex demo

Details:

  • ^ - start of string
  • ((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) - Group 1 capturing 1 IP address
  • (?:[,-](?1)){0,49} - 0 to 49 (as the subpattern above already matched 1 IP, it will sum up to 50 all in all) sequences of:
    • [,-] - a character class matching either ,or -
    • (?1) - the subroutine call that "repeats" Group 1 subpattern (unlike the backreference that matches the same value captured with a capturing group)
  • $ - end of string
Comments