正则匹配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
.

猜你喜欢

转载自www.cnblogs.com/chucklu/p/10775881.html