简体   繁体   English

IP地址/范围的正则表达式

[英]Regex for ip address/range

I have a textbox and the only input that it should take is either a single ip address or a range in the form of: 10.2.3.4-10 我有一个文本框,它应该接受的唯一输入是单个IP​​地址或以下形式的范围: 10.2.3.4-10

I have this so far: 到目前为止,我有:

string txt = "10.13.11.12-100";

        string re1 = "((?:(?: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]?))(?![\\d])";   // IPv4 IP Address 1
        string re2 = ".*?"; // Non-greedy match on filler
        string re3 = @"\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b";//"([0-255])";   // Integer Number 1

        Regex r = new Regex(re1 + re2 + re3, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Regex r2 = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match m = r.Match(txt);
        Match m3 = r2.Match(txt);
        if (m.Success || m3.Success)
        {...}

Only thing is with that, if I have 100.100.11.11-256 it will still return true since it matches m3.Success above as true. 唯一的问题是,如果我有100.100.11.11-256它仍然会返回true,因为它与上面的m3.Success匹配为true。

How to fix that? 如何解决?

For the IP Range Regex: 对于IP范围正则表达式:

^10.2.3.(?:[4-9]|10)$

For the single IP address: Regular expression to match DNS hostname or IP Address? 对于单个IP地址: 正则表达式以匹配DNS主机名或IP地址?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM