man regex.h 报告 regex.h 没有手动输入,但man 3 regex 为您提供了一个解释用于模式匹配的 POSIX 函数的页面。
The GNU C Library: Regular Expression Matching 中描述了相同的功能,它解释了 GNU C 库同时支持 POSIX.2 接口和 GNU C 库多年来一直拥有的接口。
例如,对于打印作为参数传递的哪些字符串与作为第一个参数传递的模式匹配的假设程序,您可以使用类似于以下的代码。
#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_regerror (int errcode, size_t length, regex_t *compiled);
int
main (int argc, char *argv[])
{
regex_t regex;
int result;
if (argc < 3)
{
// The number of passed arguments is lower than the number of
// expected arguments.
fputs ("Missing command line arguments\n", stderr);
return EXIT_FAILURE;
}
result = regcomp (®ex, argv[1], REG_EXTENDED);
if (result)
{
// Any value different from 0 means it was not possible to
// compile the regular expression, either for memory problems
// or problems with the regular expression syntax.
if (result == REG_ESPACE)
fprintf (stderr, "%s\n", strerror(ENOMEM));
else
fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
return EXIT_FAILURE;
}
for (int i = 2; i < argc; i++)
{
result = regexec (®ex, argv[i], 0, NULL, 0);
if (!result)
{
printf ("'%s' matches the regular expression\n", argv[i]);
}
else if (result == REG_NOMATCH)
{
printf ("'%s' doesn't the regular expression\n", argv[i]);
}
else
{
// The function returned an error; print the string
// describing it.
// Get the size of the buffer required for the error message.
size_t length = regerror (result, ®ex, NULL, 0);
print_regerror (result, length, ®ex);
return EXIT_FAILURE;
}
}
/* Free the memory allocated from regcomp(). */
regfree (®ex);
return EXIT_SUCCESS;
}
void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
char buffer[length];
(void) regerror (errcode, compiled, buffer, length);
fprintf(stderr, "Regex match failed: %s\n", buffer);
}
regcomp() 的最后一个参数至少需要为REG_EXTENDED,否则函数将使用basic regular expressions,这意味着(例如)您需要使用a\{3\} 而不是使用的a{3} extended regular expressions,这可能是你期望使用的。
POSIX.2 还有另一个通配符匹配功能:fnmatch()。它不允许编译正则表达式,或获取与子表达式匹配的子字符串,但它非常适用于检查文件名何时匹配通配符(例如,它使用FNM_PATHNAME 标志)。