正则匹配IP
https://www.cnblogs.com/leezhxing/p/4333769.html
https://devblogs.microsoft.com/oldnewthing/?p=31113
Aha, but you see, all this time diving into regular expressions
was a mistake.
Because we failed to figure out
what the actual problem was.
This was a case of somebody “solving” half of their problem
and then asking for help with the other half:
“I have a string and I want to check whether it is a dotted decimal
IPv4 address.
I know, I’ll write a regular expression!
Hey, can anybody help me write this regular expression?”
The real problem was not “How do I write a regular expression to
recognize a dotted decimal IPv4 address.”
The real problem was simply “How do I recognize a dotted decimal IPv4
address.”
And with this broader goal in mind, you recognize that limiting
yourself to a regular expression only made the problem harder.
function isDottedIPv4(s) { var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/); return match != null && match[1] <= 255 && match[2] <= 255 && match[3] <= 255 && match[4] <= 255; } WScript.StdOut.WriteLine(isDottedIPv4("127.0.0.001")); WScript.StdOut.WriteLine(isDottedIPv4("448.90210.0.65535")); WScript.StdOut.WriteLine(isDottedIPv4("microsoft.com"));
And this was just a simple dotted decimal IPv4 address.
Woe unto you if you decide you want to
parse e-mail addresses.
Don’t make regular expressions do what they’re not good at.
If you want to match a simple pattern, then match a simple pattern.
If you want to do math, then do math.
As commenter Maurits put it,
“The trick is not to spend time developing a combination hammer/screwdriver,
but just use a hammer and a screwdriver.
What is the best way of validating an IP Address?
The limitation with IPAddress.TryParse
method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5"
, it consider it as "0.0.0.5"
.
Another approach to validate an IPv4 could be following :
public bool ValidateIPv4(string ipString)
{
if (String.IsNullOrWhiteSpace(ipString))
{
return false;
}
string[] splitValues = ipString.Split('.');
if (splitValues.Length != 4)
{
return false;
}
byte tempForParsing;
return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}
It could be tested like:
List<string> ipAddresses = new List<string>
{
"2",
"1.2.3",
"1.2.3.4",
"255.256.267.300",
"127.0.0.1",
};
foreach (var ip in ipAddresses)
{
Console.WriteLine($"{ip} ==> {ValidateIPv4(ip)}");
}
The output will be:
2 ==> False
1.2.3 ==> False
1.2.3.4 ==> True
255.256.267.300 ==> False
127.0.0.1 ==> True
You can also use IPAddress.TryParse
but it has the limitations and could result in incorrect parsing.
System.Net.IPAddress.TryParse Method
Note that TryParse returns true if it parsed the input successfully, but that this does not necessarily mean that the resulting IP address is a valid one. Do not use this method to validate IP addresses.
But this would work with normal string containing at least three dots. Something like:
string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
//Valid IP, with address containing the IP
} else {
//Invalid IP
}
With IPAddress.TryParse
you can check for existence of three dots and then call TryParse
like:
public static bool ValidateIPv4(string ipString)
{
if (ipString.Count(c => c == '.') != 3) return false;
IPAddress address;
return IPAddress.TryParse(ipString, out address);
}
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了