Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do regex string replacements in pure C?

Tags:

c

string

regex

I've looked at the regex functions in the POSIX regex library and the PCRE library, but both of them don't seem to have a string replacement function. I don't want to use C++, and it would be best if I don't need to link another library (but I can if I have to). Do I need to manually do the string replacing? If so, how can I use capture groups?

like image 649
Yifan Avatar asked Nov 07 '11 23:11

Yifan


2 Answers

regex.h does not provide native support for string replacement, however it does provide subexpressions/capture groups which make it much easier. I'll assume that you're familiar with regex compilations and skip to regex execution and subexpressions.

regexec() is defined as follows in regex.h (/usr/include/):

extern int regexec (const regex_t *__restrict __preg,
        const char *__restrict __string, size_t __nmatch,
        regmatch_t __pmatch[__restrict_arr],
        int __eflags);

The first, second, and final arguments are the regex, string to be executed on and execution flags, respectively. The third and fourth arguments are used to specify an array of regmatch_t's. A regmatch_t consists of two fields: rm_so and rm_eo, which are the indices, or offsets, of the beginning and end of the matched area, respectively. Theses indices can then be used along with memcpy(), memset() and memmove()from string.h to perform string replacement.

I'll make a little example and post it later.

Good luck, and I hope that this helped.

like image 61
Lane Aasen Avatar answered Sep 28 '22 08:09

Lane Aasen


The PCRE library itself does not provide a replace function, but there is a wrapper function available at the PCRE downloads page that accepts perl style =~ s/pattern/replace/ syntax and then uses the PCRE native functions to do a substitute/replace for you. Go to http://www.pcre.org/ then click on the Download link: ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/, then the Contrib directory. The package/project you want is: pcrs-0.0.3-src.tar.gz.

Note that I have not used this myself so I cannot testify as to how well it works. It is a fairly small and simple piece of code however, so it may well serve your purpose nicely.

like image 30
ridgerunner Avatar answered Sep 28 '22 10:09

ridgerunner