用于验证 ip-list 中的 ip-range 的正则表达式 [英] regex for validating ip-range from ip-list

查看:41
本文介绍了用于验证 ip-list 中的 ip-range 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于验证 50 ips 逗号分隔列表的正则表达式:

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}$

列表示例:

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

推荐答案

您可以在这里使用 2 个东西:使用否定字符类来匹配 -,并使用子路由调用来确保您的模式保持合理的大小,并且字符串不能以 - 开头:

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}$

查看正则表达式演示

详情:

  • ^ - 字符串的开始
  • ((?:(?: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 组捕获 1 个 IP 地址
  • (?:[,-](?1)){0,49} - 0 到 49(因为上面的子模式已经匹配了 1 个 IP,所以它总共是 50) 序列:
    • [,-] - 匹配 ,-
    • 的字符类
    • (?1) - 重复"第 1 组子模式的子例程调用(与与捕获组捕获的相同 匹配的反向引用不同)
    • ^ - 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)

      这篇关于用于验证 ip-list 中的 ip-range 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆