首页 > 解决方案 > 如何在 C 中使用 PCRE 进行多个匹配

问题描述

我正在尝试使用 C 的 PCRE 库,然后使用正则表达式来匹配来自网页的 USA Senator 的多个链接。

所以要做到这一点,我需要正则表达式能够为我返回 100 个匹配项,这样我就可以将网址打印到电子邮件中。

根据我的研究,看起来 PCRE 库将成为执行此操作的方法,但我不知道如何从字符串中获取多个匹配项。

这是我将要使用的正则表达式模式

Contact:\s+<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

这是我将要使用的当前代码

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <pcre.h>

int main() {


    // initiate all used Variables
    FILE *file;
    char *buffer;
    long size;

    //Wget on Senate webpage
    system("wget -q http://www.senate.gov/general/contact_information/senators_cfm.cfm");


    // Attempt to open file
    file = fopen("senators_cfm.cfm", "r");

    if(file == NULL){

        printf("Was unable to open file \n");
        return 1;        

    }

    //Attempt to read to end of file
    fseek(file, 0L, SEEK_END);



    //Determine the number of bytes that were in the file
    size = ftell(file);

    //Attempt to allocate the number of bytes needed
    buffer = (char*) calloc(size, sizeof(char));    
    if(buffer == NULL){

        printf("Unable to allocate memory needed \n");
        return 1;
    }


    //Reset the reader to start of file
    rewind(file);


    //Read whole file into buffer
    fread(buffer, sizeof(char), size, file);


    //Close file
    fclose(file);


    //Free all information that we allocated memory for
    free(buffer);

    unlink("senators_cfm.cfm");
    return 0;
}

标签: cregexshared-librariespcre

解决方案


推荐阅读