C regex.h

C也是存在正则表达式的

Linux下regex.h知识点和使用样例

上文中有一个样例代码,进行了测试

总结一下有些注意点:

1.上述代码的匹配子串很奇怪,为什么会出现

cnt=6     a very
cnt=1     a
cnt=4     very
cyc:**************3

的结果??

2.可以使用^xxxx$来限定字符串从开头到结尾都要匹配

3.REG_NEWLINE的效果没试出来

现下想实现判断整串字符串都由数字和字母组成。

char *haa = "dasdwer213%1fsw";
    char *regex = "^[0-9a-zA-Z]+$";
    struct timeval s1, s2;
    gettimeofday(&s1, NULL);
    regex_t comment;
    regcomp(&comment, regex, REG_EXTENDED | REG_NEWLINE | REG_NOSUB);

//    regmatch_t regmatch[100]; //如果不保存结果,那么不必申请这个
    int j = regexec(&comment, haa, 0,
    NULL, 0);
    printf("Get Code
");
    if (j == REG_NOERROR) {
        printf("Success
");
    } else if (j == REG_NOMATCH) {
        printf("Failed
");
    } else {
        size_t len = regerror(j, &comment, NULL, 0);
//        printf("Error Len :%d
",len);
        char buf[len];
        bzero(buf, len);
        regerror(j, NULL, buf, len);
        printf("Error :%s
", buf);
    }
    regfree(&comment);
    gettimeofday(&s2, NULL);
    int time = (s2.tv_sec - s1.tv_sec) * 1000000 + (s2.tv_usec - s1.tv_usec);
    printf("time :%d
", time);
    return 0;
少壮不识cpp,老大方知cpp可怕
原文地址:https://www.cnblogs.com/Jacket-K/p/9259575.html