我正在寻找一些关于如何在 ANSI C 中使用正则表达式的简单示例和最佳实践。man regex.h
没有提供太多帮助。
最佳答案
正则表达式实际上不是 ANSI C 的一部分。听起来您可能在谈论 POSIX 正则表达式库,大多数(所有?)*nixes 都附带了它。这是在 C 中使用 POSIX 正则表达式的示例(基于 this ):
#include <regex.h>
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(®ex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(®ex);
或者,您可能想查看 PCRE ,一个用 C 编写的与 Perl 兼容的正则表达式库。Perl 语法与 Java、Python 和许多其他语言中使用的语法几乎相同。 POSIX语法是grep
、sed
、vi
等使用的语法
关于c - C : examples? 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1085083/