Reputation: 9733
I am looking into these to see if I can use them. I am reading:
It will be great if someone can help me understand:
The regcomp() function shall compile the regular expression contained in the string pointed to by the pattern argument and place the results in the structure pointed to by preg.
Does that mean I cannot use runtime tokens to search against? If I ask user (at runtime) to provide me what he wants to search for, I cannot do that?
Upvotes: 1
Views: 976
Reputation: 4423
Yes, you can handle regular expressions at runtime. POSIX regular expressions are handled by two main functions, regcomp()
and regexec()
(plus regfree()
and regerror()
). In the example below, regex_string
is something like "temp.*" and string_to_match
is "temp that will match"
regex_t reg;
if(regcomp(®, regex_string, REG_EXTENDED | REG_ICASE) != 0) {
fprintf(stderr, "Failed to create regex\n");
exit(1);
}
if(regexec(®, string_to_match, 0, NULL, 0) == 0) {
fprintf(stderr, "Regex matched!\n");
} else {
fprintf(stderr, "Regex failed to match!\n");
}
regfree(®);
I meant to add, regex_string is just a char *
which can be any NULL terminated string. string_to_match again can be any NULL terminated string. It is important to make the distinction that changing regex_string after you have regcomp()
'd does NOT change the regex actually being matched against with regexec()
. For this you would need to regfree()
and then re-regcomp()
.
Upvotes: 3
Reputation: 121599
"The regcomp() function shall compile the regular expression contained in the string..."
Q: Does that mean I cannot use runtime tokens to search string against?
No, it only means that, once you've got the string, regcomp() will compile the regular expression so that it can be used with one or more input strings.
You can get create both the regular expression and/or any target strings either at compile time or at runtime.
Upvotes: 1
Reputation: 9733
I guess I found a good example at mij.oltrelinux.com/devel/unixprg/
/* compiles the RE. If this step fails, reveals what's wrong with the RE */
if ( (err = regcomp(&myre, argv[1], REG_EXTENDED)) != 0 ) {
regerror(err, &myre, err_msg, MAX_ERR_LENGTH);
printf("Error analyzing regular expression '%s': %s.\n", argv[1], err_msg);
return 1;
}
Upvotes: 0