LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Could anyone show me a simple example of regex or pcre program on linux C? (https://www.linuxquestions.org/questions/linux-software-2/could-anyone-show-me-a-simple-example-of-regex-or-pcre-program-on-linux-c-787524/)

bellhuang 02-07-2010 01:44 AM

Could anyone show me a simple example of regex or pcre program on linux C?
 
I am trying to use regex or pcre to find out the matched from multiple textfiles. Could anyone share me a example of how to write a relative program on linux C? Thanks in advance.

neonsignal 02-07-2010 02:56 AM

pcre comes with a demo program.

bellhuang 02-07-2010 05:44 AM

why following program can't work?
#include<stdio>
#include<sys/types.h>
#include<regex.h>

int main()
{**int status;
char str[]="abcd";
char pattern[]="a.";
* **regex_t *preg;
* **regcomp(preg, pattern, REG_EXTENDED|REG_NOSUB)
status=regexec(preg,str,1,NULL,0);
* * while(status==0) printf("ok");
regfree(preg);
}

neonsignal 02-07-2010 06:05 AM

It crashes because the program does not allocate space for the pattern storage area that preg points to. With this allocated, it will work:

Code:

#include <stdio.h>
#include <regex.h>
int main()
{
    int status;
    char str[]="abcd";
    char pattern[]="a.";
    regex_t reg;
    regcomp(&reg, pattern, REG_EXTENDED|REG_NOSUB);
    status=regexec(&reg,str,1,NULL,0);
    if (status==0)
        printf("match\n");
    else
        printf("no match\n");
    regfree(&reg);
}



All times are GMT -5. The time now is 06:25 PM.