linux下用C写正则匹配IP和邮箱

一时想娱乐一下,写了一段小程序,使用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;
}

string
strtolower(string str)
{
    string tmp;
    for(size_t i=0; i<str.length(); ++i)
        tmp.push_back(tolower(str[i]));

    return tmp;
}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值