linux下用C寫正則匹配IP和郵箱

來源:互聯網
上載者:User

一時想娛樂一下,寫了一段小程式,使用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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.