正则表达式用于从字符串缓存区里搜索是否有满足条件的字符段落(可以无、有1个,多个等等情况)。
java/python/c都有开发接口。
基本套路都是:
[1]正则模式编译:
后面匹配时可以直接使用,加快效率;
int regcomp(regex_t *compiled, const char *pattern, int cflags);
【2】匹配:
int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)
注意:如果要看是否输入的string完整匹配正则,需要看matchptr内的字符区间是否涵盖了整个字符串长度。
【3】使用完毕释放:
void regfree (regex_t *compiled)
【4】错误信息查询:
size_t regerror (int errcode, regex_t *compiled, char *buffer, size_t length)
简单示例:在这里插入代码片
#include<stdio.h>
#include<sys/types.h>
#include<regex.h>
#include <string.h>
void print_match(regmatch_t * pmatch, char * buf)
{
int i;
for(i=pmatch->rm_so;i<pmatch->rm_eo;++i){
putchar(buf[i]);
}
putchar('\n');
}
int reg_match(regex_t* pattern,char* buf){
regmatch_t pmatch[1];
const size_t nmatch=1;
//执行正则表达式和缓存的比较
int status=regexec(pattern, buf, nmatch, pmatch, 0);
if(status==REG_NOMATCH)
printf("No match!\n");
else if(0 == status){
int length = pmatch[0].rm_eo - pmatch[0].rm_so;
if(length == strlen(buf)){
printf(" %s 完全匹配成功!==> ", buf);
}else{
printf(" %s 部分匹配成功 ***> ", buf);
}
//打印匹配的字符串
print_match(&pmatch[0], buf);
}
return status;
}
int main(){
regex_t regFileName;
//编译正则模式
int rc = regcomp(®FileName, "[0-9A-Za-z_\\.-]+", REG_EXTENDED) ;
if(0 == rc){
reg_match(®FileName, "abc.name");
reg_match(®FileName, "ab11c.name");
reg_match(®FileName, "abc22.name");
reg_match(®FileName, "abc.33");
reg_match(®FileName, "abc.--33");
reg_match(®FileName, "abc.-33.aa.c");
reg_match(®FileName, "abc.,-33.aa.c");
reg_match(®FileName, "abc--__.33");
reg_match(®FileName, "abc-@__.33");
reg_match(®FileName, "abc-#__.33");
reg_match(®FileName, "abc-343~__.33");
regfree(®FileName);
}else{
printf("reg compiled errror\n");
char errBuf[1024];
regerror(rc, ®FileName, errBuf, 1024);
printf("reg error: %s\n", errBuf);
}
return 0;
}
本文介绍了如何在C语言中使用正则表达式进行字符串匹配。通过`regcomp`、`regexec`和`regfree`等函数,演示了从编译正则模式到执行匹配和释放资源的完整过程,并提供了一个简单的示例代码,展示了如何检查字符串是否符合特定的字符模式。

9099

被折叠的 条评论
为什么被折叠?



