如何檢查是否為合法IP? (.NET) (C++/CLI) (C/C++) (Reqular Expression)

Abstract
檢查是否為合法IP,不需hardcode了,透過Regular Expression,只要一行就可以。

Introduction
有網友Email問我如何用C++/CLI檢查IP,當然自己parse也可以,不過既然用了.NET平台,而.NET又支援Regular Expression,這種檢查的字串的程式,用Regular Expression是首選。

C++/CLI / CheckIP.cpp

 1 /* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : ChcekIP.cpp
 5Compiler    : Visual C++ 8.0 / C++/CLI
 6Description : Demo how to validate IP
 7Release     : 05/17/2007 1.0
 8*/

 9 #include  " stdafx.h "
10 using   namespace  System;
11 using   namespace  System::Text::RegularExpressions;
12
13 bool  isValidIP(String ^   const %  ip)  {
14  Regex^ reg = gcnew Regex("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
15  Match^ match = reg->Match(ip);
16  
17  return match->Success;
18}

19
20 int  main()  {
21  String^ s1 = "140.290.1.1";
22  String^ s2 = "140.113.1.1";
23  
24  Console::WriteLine(isValidIP(s1));
25  Console::WriteLine(isValidIP(s2));
26}


執行結果

False
True


Reference
Sample Regular Expressions

你可能感兴趣的:(express)