How to use RegEx?

Running regular expressions in C # or PHP is now very easy for me. However, I currently have a need to use regex in C. And I don't quite understand how to use regcomp or regexec. This is definitely due to my lack of experience in C.

+4
source share
5 answers

This can lead to a run as you specify regex(3) functions. The following is a trivial program corresponding to its arguments. However, if you are relatively new to C, you need to go slowly with regex(3) , since you will work with pointers and arrays and regmatch_t - offsets, lions and tigers and bears are added.;)

 $ ./regexec '[[:digit:]]' 56789 alpha " " foo12bar matched: 56789 matched: foo12bar $ ./regexec '[[:digit:]](foo' error: Unmatched ( or \( $ ./regexec '[' error: Invalid regular expression 

... and source:

 #include <sys/types.h> #include <regex.h> #include <stdio.h> int main(int argc, char **argv) { int r; regex_t reg; ++argv; /* Danger! */ if (r = regcomp(&reg, *argv, REG_NOSUB|REG_EXTENDED)) { char errbuf[1024]; regerror(r, &reg, errbuf, sizeof(errbuf)); printf("error: %s\n", errbuf); return 1; } for (++argv; *argv; ++argv) { if (regexec(&reg, *argv, 0, NULL, 0) == REG_NOMATCH) continue; printf("matched: %s\n", *argv); } return 0; } 
+5
source

Use the PCRE library. Examples are included in the source in the demo/ directory. Direct link to pcredemo.c .

+7
source

You need a library that provides it, and there are several options. PCRE is one.

+2
source

There is also libslack (str) - a string module:

http://libslack.org/manpages/str.3.html

+1
source

Gnu C library has regex library

0
source

All Articles