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

标签 c regex

我正在寻找一些关于如何在 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/

相关文章:

java - Java中的类不就相当于c中的结构吗

c - 在困惑中,我们可以从 table_layout 中删除所有参与者吗?

匹配 PowerShell 代码中的 "here strings"的正则表达式

c - 在 Linux/C 编程中,使用函数 write 也会在缓冲区上移动指标吗?

c - 请有人帮我解释链表吗?

c - 使用嵌套结构数组进行结构初始化

java - 如何从字符串中提取单词?

Python正则表达式搜索并替换所有出现的地方

PHP:仅显示每个单词的第一个字母 + 包括标点符号

regex - 正则表达式匹配网址路径-Golang与Gorilla Mux