最近在处理MQTT协议的主题碰到类似"adc/+/Request/#/MODBUS/mb1"的字符串,想着可以使用正则表达式来处理。
LINUX下提供了函数簇来是使用正则表达式,直接man regcomp可以得到
1 #include <sys/types.h> 2 #include <regex.h> 3 4 int regcomp(regex_t *preg, const char *regex, int cflags); 5 6 int regexec(const regex_t *preg, const char *string, size_t nmatch, 7 regmatch_t pmatch[], int eflags); 8 9 size_t regerror(int errcode, const regex_t *preg, char *errbuf, 10 size_t errbuf_size); 11 12 void regfree(regex_t *preg);
具体过程是先使用regcomp变一下pattern,然后可以使用rgexec得到结果,或者使用regerror取获取具体错误,然后使用regfree,上代码
#include <stdio.h> #include <string.h> #include <regex.h> // 提取子串 char* getsubstr(char *s, regmatch_t *pmatch) { static char buf[100] = {0}; memset(buf, 0, sizeof(buf)); memcpy(buf, s+pmatch->rm_so, pmatch->rm_eo - pmatch->rm_so); return buf; } int main(void) { regmatch_t pmatch; regex_t reg; //const char *pattern = "[a-z]+"; // 正则表达式 //char buf[] = "HELLOsaiYear2012@gmail.com"; // 待搜索的字符串 const char *pattern = "[a-zA-Z_#+]+"; // 正则表达式 char buf[] = "adc/+/Request/#/MODBUS/mb1"; // 待搜索的字符串 regcomp(®, pattern, REG_EXTENDED); //编译正则表达式 int offset = 0; while(offset < strlen(buf)) { int status = regexec(®, buf + offset, 1, &pmatch, 0); /* 匹配正则表达式,注意regexec()函数一次只能匹配一个,不能连续匹配,网上很多示例并没有说明这一点 */ if(status == REG_NOMATCH) printf("No Match\n"); else if(pmatch.rm_so != -1) { printf("Match:\n"); char *p = getsubstr(buf + offset, &pmatch); printf("[%d, %d]: %s\n", offset + pmatch.rm_so + 1, offset + pmatch.rm_eo, p); } offset += pmatch.rm_eo; } regfree(®); //释放正则表达式 return 0; }
特别要注意,匹配正则表达式,注意regexec()函数一次只能匹配一个,不能连续匹配,网上很多示例并没有说明这一点。
int status = regexec(®, buf + offset, 1, &pmatch, 0);
所以这里的offset要每次加一。
写这篇博客参考了https://www.cnblogs.com/stlong/p/6289107.html,感兴趣可以移步。
原文:https://www.cnblogs.com/njit-sam/p/12672879.html