boost 命令行解析库,包括正则表达式检查IP格式
示例如下:
1 #include <boost/program_options.hpp> 2 #include <boost/foreach.hpp> 3 #include <boost/xpressive/xpressive_dynamic.hpp> 4 5 using namespace boost; 6 namespace po = boost::program_options; 7 8 #include <iostream> 9 #include <algorithm> 10 #include <iterator> 11 using namespace std; 12 13 bool CheckIP(const char *ip) 14 { 15 boost::xpressive::cregex reg_ip = boost::xpressive::cregex::compile("(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"); 16 return boost::xpressive::regex_match(ip, reg_ip); 17 } 18 19 int main(int argc, char* argv[]) 20 { 21 try { 22 int opt; 23 int portnum; 24 po::options_description desc("Allowed options"); 25 desc.add_options() 26 ("help,h", "produce help message") 27 ("optimization,o", po::value<int>(&opt)->default_value(10), 28 "optimization level") 29 ("verbose,v", po::value<int>()->implicit_value(1), 30 "enable verbosity (optionally specify level)") 31 ("listen,l", po::value<int>(&portnum)->implicit_value(1001) 32 ->default_value(0,"no"), 33 "listen on a port.") 34 ("ip,i", po::value<string>(), "IP address") 35 ("input-file,f", po::value< vector<string> >(), "input file") 36 ; 37 38 po::variables_map vm; 39 po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); 40 po::notify(vm); 41 42 if (argc == 1 || vm.count("help")) { 43 cout << "Usage: \n"; 44 cout << desc << endl;; 45 return 0; 46 } 47 48 if (vm.count("input-file")) { 49 string path_str(""); 50 BOOST_FOREACH(string path, vm["input-file"].as< vector<string> >()) 51 path_str += path + " "; 52 cout << "Input file are: " << path_str << endl; 53 } 54 55 if (vm.count("ip")) { 56 string ip_str = vm["ip"].as<string>(); 57 58 if (CheckIP(ip_str.c_str())) { 59 cout << "IP address is: " << ip_str << "\n"; 60 } else { 61 cout << "Bad IP format!\n"; 62 return 1; 63 } 64 } 65 66 if (vm.count("verbose")) { 67 cout << "Verbosity enabled. Level is " << vm["verbose"].as<int>() 68 << "\n"; 69 } 70 71 cout << "Optimization level is " << opt << "\n"; 72 cout << "Listen port is " << portnum << "\n"; 73 } catch(std::exception& e) { 74 cout << e.what() << "\n"; 75 return 1; 76 } 77 78 return 0; 79 }