gpt4 book ai didi

c - C : examples? 中的正则表达式

转载 作者:太空狗 更新时间:2023-10-29 16:14:13 27 4
gpt4 key购买 nike

我正在寻找一些关于如何在 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(&regex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);

或者,您可能想查看 PCRE ,一个用 C 编写的与 Perl 兼容的正则表达式库。Perl 语法与 Java、Python 和许多其他语言中使用的语法几乎相同。 POSIX语法是grepsedvi等使用的语法

关于c - C : examples? 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1085083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com