This code example shows the usage of the Regular Expressions API. It can also be found at speect/engine/examples/base/strings/regexp_example.c, and be compiled with the WANT_EXAMPLES build option.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | #include <stdio.h>
#include "speect.h"
int main()
{
s_erc error = S_SUCCESS;
const char *string = "A soufflé is a light, fluffy, baked cake.";
/* Groups g(1) g(2) g(3) */
const char *regex = "(.*) (.*é) (.*)";
s_regexsub *rsub;
s_regex *rx;
int rv;
/*
* initialize speect
*/
error = speect_init(NULL);
if (error != S_SUCCESS)
{
printf("Failed to initialize Speect\n");
return 1;
}
/*
* compile regular expression, "." metacharacter does not match newline.
*/
rx = s_regex_comp(regex, S_DOT_EXCLD_NEWLINE, &error);
if (S_CHK_ERR(&error, S_CONTERR,
"main",
"Failed to compile regular expression"))
goto quit;
/*
* try to match the compiled regular expression with
* the string "A soufflé is a light, fluffy, baked cake."
* The second group, "(.*é)" must match the word "soufflé".
*/
rv = s_regex_match(rx, string, &rsub, &error);
if (S_CHK_ERR(&error, S_CONTERR,
"main",
"Call to \"s_regex_match\" failed"))
{
S_FREE(rx);
goto quit;
}
if (rv > 0)
{
printf("string matched\n");
}
else if (rv < 0)
{
printf("ran out of space\n");
}
else
{
printf("no match\n");
}
/*
* get sub-string group matches
* Group 0 is always the whole match, i.e. "A soufflé is a light, fluffy, baked cake."
* Group 1 should be "A"
* Group 2 should be "soufflé"
* Group 3 should be "is a light, fluffy, baked cake."
*
* Note that the spaces around "soufflé" are not grouped.
*/
if (rv > 0)
{
uint8 num_matches;
uint i;
/*
* get number of groups
*/
num_matches = s_regexsub_num_groups(rsub, &error);
if (S_CHK_ERR(&error, S_CONTERR,
"main",
"Failed to get number of sub-match groups"))
{
S_FREE(rx);
S_FREE(rsub);
goto quit;
}
for (i = 0; i < num_matches; i++)
{
char *sub_string;
/*
* get specific group and print. Group 0 is always
* the whole match.
*/
sub_string = s_regexsub_group(rsub, i, &error);
if (S_CHK_ERR(&error, S_CONTERR,
"main",
"Failed to get sub-match group %d", i))
{
S_FREE(rx);
S_FREE(rsub);
goto quit;
}
if (sub_string != NULL)
{
printf("group [%d] = \"%s\"\n", i, sub_string);
S_FREE(sub_string);
}
else
printf("group [%d] = NULL\n", i);
}
}
/*
* free memory of regexp and sub-matches
*/
S_FREE(rx);
S_FREE(rsub);
quit:
/*
* quit speect
*/
error = speect_quit();
if (error != S_SUCCESS)
{
printf("Call to 'speect_quit' failed\n");
return 1;
}
return 0;
}
|