Drew Drew - 7 days ago 7
C Question

Using Regular Expression to extract word in a string in C

I'm trying to extract a small substring from a string of words in c. I did it in a previous program written in python using this code:

out_block = "".join(re.findall(r'.FT off(.*?).FT on',finaltext,re.DOTALL))


The code extracts all the characters in between
.FT off
and
.FT on
and passes it to
out_block
as a string.

I wanted to know how to do the same using regular expressions but in C

How would I convert this code to a C code that does the exact same thing?

Answer

Basicly you do this:

#include <sys/types.h>
#include <regex.h>

regex_t finder;
if (0 != regcomp(&finder, "regex-string", 0)) { error handling }

You might need to adjust your regex string above.

After that you can do any number of times:

regmatch_t match[N_MATCH];
if (0 == regexec(&finder, "haystack", N_MATCH, match, 0)) {
    process matches
} else {
    no match
}

Clean up using regfree and get error messages (in regcomp) using regerror.

For more details, consult man page regex(3).

Comments