嘗試用C正則運算式決議配置資訊okcode,以分號;為分隔符,提取各段資訊,結果只匹配到第一個,即[1,2],
這個正則運算式應該是沒有問題的,我用python的正則運算式re.findall()是可以正常匹配的,不知道為什么C沒有匹配出其他欄位資訊,
不知道是代碼問題,還是正則運算式的問題,請高手賜教!
代碼如下:
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *okcode = "[1,2];[5,6];[7,10);3";
char *pattern = "(\\[|\\()\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*(\\)|\\])|([0-9]+);{0,1}";
char buf[1024];
char match[100];
int res;
regex_t re;
static const size_t nmatch = 50;
regmatch_t pmatch[50];
/* 編譯正則運算式*/
res = regcomp(&re, pattern, REG_EXTENDED);
if (res) {
regerror(res, &re, buf, sizeof(buf));
fprintf(stderr, "%s: pattern '%s' \n", buf, pattern);
return 1;
}
/* 應用正則運算式進行匹配 */
res = regexec(&re, okcode, nmatch, pmatch, 0);
if (res == REG_NOMATCH) {
printf("no match\n");
regfree(&re);
return 2;
}
else if (res != 0) {
regerror(res, &re, buf, sizeof(buf));
fprintf(stderr, "res: %s\n", buf);
regfree(&re);
return 3;
}
/* 輸出處理結果 */
int i;
for (i = 0; i < nmatch && pmatch[i].rm_so != -1; ++i) {
int len = pmatch[i].rm_eo - pmatch[i].rm_so;
if (len) {
memset(match, 0, sizeof(match));
memcpy(match, okcode + pmatch[i].rm_so, len);
printf("[%d]: %s\n", i, match);
}
}
/* 釋放正則運算式 */
regfree(&re);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/17635.html
標籤:C語言
上一篇:找大神幫忙瞅瞅哪塊邏輯有問題
下一篇:常指標和指標常量
