kRicha kRicha - 1 year ago 65
PHP Question

regex for validating ip-rage 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:,

now i need to support list, like this:,

i try, to use subpatterns, but nothing happened

can somebody provide regex example for validating this string:

Answer Source

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 -:


See the regex demo


  • ^ - 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download