X-Git-Url: http://git.ozlabs.org/?p=ccan;a=blobdiff_plain;f=ccan%2Fstr_talloc%2Fstr_talloc.h;h=3c65f9f84691ef68e0f1d9e695e59b3edba0ddae;hp=50cea2dcb3b4ce6db7d3bcd968b41215a1a475e6;hb=fa64b4599366818ea546c7db026f37d987d181a8;hpb=053f9398c5959d070b7092653ec8f222200ab463 diff --git a/ccan/str_talloc/str_talloc.h b/ccan/str_talloc/str_talloc.h index 50cea2dc..3c65f9f8 100644 --- a/ccan/str_talloc/str_talloc.h +++ b/ccan/str_talloc/str_talloc.h @@ -63,4 +63,47 @@ char **strsplit(const void *ctx, const char *string, const char *delims, * } */ char *strjoin(const void *ctx, char *strings[], const char *delim); + +/** + * strreg - match and extract from a string via (extended) regular expressions. + * @ctx: the context to tallocate from (often NULL) + * @string: the string to try to match. + * @regex: the regular expression to match. + * ...: pointers to strings to allocate for subexpressions. + * + * Returns true if we matched, in which case any parenthesized + * expressions in @regex are allocated and placed in the char ** + * arguments following @regex. NULL arguments mean the match is not + * saved. The order of the strings is the order + * of opening braces in the expression: in the case of repeated + * expressions (eg "([a-z])*") the last one is saved, in the case of + * non-existent matches (eg "([a-z]*)?") the pointer is set to NULL. + * + * Allocation failures or malformed regular expressions return false. + * + * See Also: + * regcomp(3), regex(3). + * + * Example: + * // Given 'My name is Rusty' outputs 'Hello Rusty!' + * // Given 'my first name is Rusty Russell' outputs 'Hello Rusty Russell!' + * // Given 'My name isnt Rusty Russell' outputs 'Hello there!' + * int main(int argc, char *argv[]) + * { + * char *person, *input; + * + * // Join args and trim trailing space. + * input = strjoin(NULL, argv+1, " "); + * if (strlen(input) != 0) + * input[strlen(input)-1] = '\0'; + * + * if (strreg(NULL, input, "[Mm]y (first )?name is ([A-Za-z ]+)", + * NULL, &person)) + * printf("Hello %s!\n", person); + * else + * printf("Hello there!\n"); + * return 0; + * } + */ +bool strreg(const void *ctx, const char *string, const char *regex, ...); #endif /* CCAN_STR_TALLOC_H */