開發環境:VS2017
使用2.7的regex庫,應該是最新的。
regex函式原型
int regexec(const regex_t *preg, const char *string, size_t nmatch,regmatch_t pmatch[], int eflags);
在匹配字串的程序中,用正則尋找連續數字串,現在遇到兩個問題:
1.對于 "we12312332qwwww d1246Xdes"這個字串,我用"\[0-9]{4}"匹配連續4個數字,但是每次regex只匹配了第一個"1231"就回傳了,后續"2332""1246"匹配不到,我填入的pmatch陣列引數支持最多25個匹配結果,但是除了第一個有對應字符的資訊,其他的都是-1.如果我把第一個1231去掉,又能匹配接下來的2332.
2.有個疑問,假如我匹配“1234”中的連續2個數字串,有辦法匹配出"12"、"23"、"34"這樣的結果嗎?因為我現在想做一個臟資料處理可能要考慮這個。
以上兩個問題,希望各位大佬指教

#include <stdio.h>
#include <string.h>
#include "regex.h"
int main(int argc, char *argv[])
{
int len;
regex_t re;
regmatch_t subs[25];
char matched[1024];
char errbuf[128];
int err = 0, i = 0;
char src[1024] = { "we12312332qwwww d1246Xdes" };
char pattern[1024] = { "\[0-9]{4}" };
/*編譯正則運算式*/
err = regcomp(&re, pattern, REG_EXTENDED);
if (err)
{
len = regerror(err, &re, errbuf, sizeof(errbuf));
printf("error: regcomp: %s\r\n", errbuf);
return 1;
}
printf("Total has subexpression: %d\n", re.re_nsub);
/*執行模式匹配*/
err = regexec(&re, src, 25, subs, 0);
if (err == REG_NOMATCH)
{
printf("no match...\r\n");
regfree(&re);
return 0;
}
else if (err)
{
len = regerror(err, &re, errbuf, sizeof(errbuf));
printf("error: regexec: %s\r\n", errbuf);
return 1;
}
printf("OK , has matched...\r\n");
for (i = 0; i <= re.re_nsub; i++)
{
len = subs[i].rm_eo - subs[i].rm_so;
if (0 == i)
{
printf("begin: %d, len = %d \r\n",subs[i].rm_so, len);
}
else
{
printf("subexpression %d begin: %d, len = %d ", i, subs[i].rm_so, len);
}
memcpy(matched, src + subs[i].rm_so, len);
matched[len] = '\0';
printf("match: %s\n", matched);
}
regfree(&re);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/237337.html
標籤:C語言
上一篇:如何高效地截掉文本檔案前面部分?
