regex for validating ip-range from ip-list

做~自己de王妃 提交于 2019-12-23 13:23:43

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/40847544/regex-for-validating-ip-range-from-ip-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!