按行读取文件并匹配模式-C
创始人
2024-08-22 02:00:18
0
  1. 使用 fgets() 函数按行读取文件。

  2. 使用正则表达式库 regex.h 中的 regcomp() 和 regexec() 函数进行模式匹配。

下面是一个示例代码:

#include 
#include 

int main() {
    FILE *fp;
    char line[100];
    regex_t regex;
    int reti;

    /* Compile regular expression */
    reti = regcomp(®ex, "^\\d+\\s+[A-Za-z]+", 0);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        return 1;
    }

    /* Open file */
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    /* Read file line by line and match pattern */
    while (fgets(line, 100, fp) != NULL) {
        /* Execute regular expression */
        reti = regexec(®ex, line, 0, NULL, 0);
        if (!reti) {
            printf("Matched: %s", line);
        } else if (reti == REG_NOMATCH) {
            printf("No match: %s", line);
        } else {
            regerror(reti, ®ex, line, sizeof(line));
            fprintf(stderr, "Regex match failed: %s\n", line);
            return 1;
        }
    }

    /* Free compiled regular expression */
    regfree(®ex);

    /* Close file */
    fclose(fp);

    return 0;
}

这段代码可以从名为 "file.txt" 的文件中读取每一行,然后使用正则表达式"^\d+\s+[A-Za-z]+"进行匹配。如果匹配成功,则输出该行。上述正则表达式匹配的是一个或多个数字,一个或多个空格,一个或多个字母的字符串。在实际应用中,请根据需求自行修改正则表达式。

相关内容

热门资讯

透视计算!hhpoker脚本下... 透视计算!hhpoker脚本下载(透视)好像是有挂(详细辅助细节揭秘)1、ai辅助优化,发牌逻辑科技...
每日必看推荐!wepoker破... 每日必看推荐!wepoker破解器有用吗,wepoker辅助器官方,技巧教程(有挂神器)准备好在we...
透视好友房!wepoker怎么... 透视好友房!wepoker怎么发冤家牌(透视)一贯有挂(详细辅助黑科技教程)1、在ai机器人技巧中,...
实测必看!wepoker可以免... 实测必看!wepoker可以免费玩吗,wepoker的辅助器,黑科技教程(有挂透明)是一款可以让一直...
透视能赢!大菠萝789辅助器下... 透视能赢!大菠萝789辅助器下载(透视)都是真的是有挂(详细辅助wpk教程)透视能赢!大菠萝789辅...
新手必备!hhpoker德州挂... 新手必备!hhpoker德州挂真的有吗,wepoker免费透视,辅助教程(有挂透明);实战中需综合运...
透视透视!wepoker有脚本... 透视透视!wepoker有脚本吗(透视)好像真的是有挂(详细辅助系统教程)软件透明挂微扑克wpk插件...
必看攻略!aapoker脚本,... 必看攻略!aapoker脚本,aapoker怎么提高中牌率,专业教程(有挂透视);支持2-10人实时...
透视脚本!aapoker辅助软... 透视脚本!aapoker辅助软件合法吗(透视)都是存在有挂(详细辅助科技教程)1、系统规律教程、辅助...
必备科技!wepoker有机器... 必备科技!wepoker有机器人吗,wepoker私人局透视,靠谱教程(有挂软件)科技教程也叫必备教...