【C语言正则表达式】一个示例
生活随笔
收集整理的這篇文章主要介紹了
【C语言正则表达式】一个示例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
正則表達式用于從字符串緩存區(qū)里搜索是否有滿足條件的字符段落(可以無、有1個,多個等等情況)。
java/python/c都有開發(fā)接口。
基本套路都是:
[1]正則模式編譯:
后面匹配時可以直接使用,加快效率;
【2】匹配:
int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)注意:如果要看是否輸入的string完整匹配正則,需要看matchptr內(nèi)的字符區(qū)間是否涵蓋了整個字符串長度。
【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;//執(zhí)行正則表達式和緩存的比較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; }總結(jié)
以上是生活随笔為你收集整理的【C语言正则表达式】一个示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jemter web端录制
- 下一篇: RGB图像转灰度图像的原理