const char *pattern="[a-zA-Z]{6,}tion";
Now, how to use this? Well, it turns out that first we have to compile it into a structure called a regex_t, using the function regcomp.regex_t rx; regcomp(&rx,pat,REG_EXTENDED);We must also make a variable of type regmatch_t to hold the data we'll get from the regex. We then call regexec to match the pattern to a string:
char s[100]; fgets(s,100,stdin); regmatch_t res; int matched regexec(&rx,s,1,&res,0);Now, matched will be 0 if it matched, or E_NOMATCH if it didn't. res.rm_so contains the coordinate of the start of the matching substring if any, and res.rm_eo contains the end coordinate.
You can call regexec over and over on different strings. Eventually, though, you'll want to stop using the regex. Then you should call regfree to free the memory used by the compiled regex.
regfree(&rx);To demonstrate, here is a function which matches a string to a pattern and returns a copy of the result.
regmatch_t rxmatch(char *s,char *pat){//returns a dst copy of matching substring.
regex_t rx;
regmatch_t res;
regcomp(&rx,pat,REG_EXTENDED);
regexec(&rx,s,1,&res,0);
regfree(&rx);
return res;
}
Generally though you should compile each regex you use only once, especially if you use a single regex on many strings.
Edited by Alexander, 03 December 2011 - 01:56 AM.


Sign In
Create Account


Back to top









