0

I need to to substitution in a string in C. It was recommended in one of the answers here How to do regex string replacements in pure C? to use the PCRS library. I downloaded PCRS from here ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/Contrib/ but I'm confused as to how to use it. Below is my code (taken from another SE post)

            const char *error;
            int   erroffset;
            pcre *re;
            int   rc;
            int   i;
            int   ovector[100];

            char *regex = "From:([^@]+).*";
            char str[]  = "From:regular.expressions@example.com\r\n";
            char stringToBeSubstituted[] = "gmail.com";

            re = pcre_compile (regex,          /* the pattern */
                               PCRE_MULTILINE,
                               &error,         /* for error message */
                               &erroffset,     /* for error offset */
                               0);             /* use default character tables */
            if (!re)
            {
                printf("pcre_compile failed (offset: %d), %s\n", erroffset, error);
                return -1;
            }

            unsigned int offset = 0;
            unsigned int len = strlen(str);
            while (offset < len && (rc = pcre_exec(re, 0, str, len, offset, 0, ovector, sizeof(ovector))) >= 0)
            {
                for(int i = 0; i < rc; ++i)
                {
                    printf("%2d: %.*s\n", i, ovector[2*i+1] - ovector[2*i], str + ovector[2*i]);
                }
                offset = ovector[1];
            }

As opposed to 'pcre_compile' and 'pcre_exec' what functions do I need to use from PCRS?

Thanks.

Community
  • 1
  • 1
user13107
  • 3,239
  • 4
  • 34
  • 54

1 Answers1

0

Simply follow the instructions in the INSTALL file:

To build PCRS, you will need pcre 3.0 or later and gcc.

Installation is easy: ./configure && make && make install Debug mode can be enabled with --enable-debug.

There is a simple demo application (pcrsed) included.

PCRS provides the following functions documented in the man page pcrs.3:

  • pcrs_compile
  • pcrs_compile_command
  • pcrs_execute
  • pcrs_execute_list
  • pcrs_free_job
  • pcrs_free_joblist
  • pcrs_strerror

Here's an online version of the man page. To use these functions, include the header file pcrs.h and link your program against the PCRS library using the linker flag -lpcrs.

nwellnhof
  • 32,319
  • 7
  • 89
  • 113