一時想娛樂一下,寫了一段小程式,使用linux的正則庫匹配ip和email地址
#include <sys/types.h>#include <regex.h>#include <iostream>#include <string>#include <map>#include <algorithm>#include <cctype>using namespace std;string strtolower(string str);int main(int argc, const char *argv[]){ if (argc < 3) { cout << "usage: regex <type> string" << endl; return 0; } string type, str; int result, z, reti; regmatch_t pm[10]; const size_t nmatch = 10; type = string((const char*)argv[1]); str = string(argv[2]); map<string, string> regs; map<string, int> types; regs["ip"] = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; regs["email"] = "[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+\\.[a-zA-Z0-9_.-]+"; types["ip"] = 1; types["email"] = 2; regex_t preg; type = strtolower(type); reti = regcomp(&preg, regs[type].c_str(), REG_EXTENDED|REG_NOSUB); if (reti) { char errbuf[1024]; regerror(reti, &preg, errbuf, 1024); cout << "Could not compile regex with message " << errbuf;exit(1); } result = regexec(&preg, str.c_str(), 0, NULL, 0); switch (types[type]) { case 1 : if (result == REG_NOMATCH) cout << "regcomp ip no match" << " reg express " + regs[type] << endl; else if (!result) { cout << "match" << endl; } break; } regfree(&preg); return 0;}stringstrtolower(string str){ string tmp; for(size_t i=0; i<str.length(); ++i) tmp.push_back(tolower(str[i])); return tmp;}