正则表达式的C代码实例
时间: 2023-04-02 16:04:08 浏览: 87
可以使用C语言中的正则表达式库regex.h来实现正则表达式的功能。以下是一个简单的C代码实例:
#include <stdio.h>
#include <regex.h>
int main()
{
regex_t reg;
int ret;
char *pattern = "hello.*world";
char *str = "hello, this is a world of wonders!";
ret = regcomp(®, pattern, REG_EXTENDED);
if (ret != ) {
printf("Failed to compile regex pattern\n");
return 1;
}
ret = regexec(®, str, , NULL, );
if (ret == ) {
printf("Match found!\n");
} else if (ret == REG_NOMATCH) {
printf("No match found\n");
} else {
printf("Error executing regex\n");
}
regfree(®);
return ;
}
这个例子中,我们使用了regex.h库中的regcomp()和regexec()函数来编译和执行正则表达式。我们定义了一个简单的正则表达式模式"hello.*world",它匹配以"hello"开头,以"world"结尾,中间可以是任意字符的字符串。我们将这个模式编译成一个regex_t类型的结构体,然后使用regexec()函数来执行匹配操作。如果匹配成功,函数返回,否则返回REG_NOMATCH。最后,我们使用regfree()函数释放regex_t结构体的内存。