版本一
多次解析出错
c
#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <stdlib.h>
int main()
{
char *pattern = "\x02\xf1\x03SX[a-zA-Z0-9]{2}[.;]";
regex_t reg;
int rc = regcomp(®, pattern, REG_EXTENDED);
if(rc != 0) {
printf("regcomp error: ret=%d\n", rc);
}
char *str = "11\x02\xf1\x03SX11;465\x02\xf1\x03SX11.";
int size = strlen(str);
unsigned int offset = 0;
regmatch_t pm;
size_t nmatch = 1;
while (offset < size)
{
rc = regexec(®, str + offset, nmatch, &pm, REG_EXTENDED);
if(rc != 0) {
printf("regexec error: ret=%d\n", rc);
} else {
char *part_str = strndup(str + offset + pm.rm_so, pm.rm_eo - pm.rm_so);
offset += pm.rm_eo;
printf("%s start:%d end:%d offset:%d\n", part_str, pm.rm_so, pm.rm_eo, offset);
free(part_str);
part_str = NULL;
}
}
regfree(®);
return 0;
}
版本二
c
#include <iostream>
#include <regex>
using namespace std;
int main()
{
string str = "\x02\xf1\x03SX11;060F20?.\x11SX32.";
smatch result;
regex pattern("SX[a-zA-Z0-9]{2}[.;]"); //匹配四个数字
//迭代器声明
string::const_iterator iterStart = str.begin();
string::const_iterator iterEnd = str.end();
string temp;
while (regex_search(iterStart, iterEnd, result, pattern))
{
temp = result[0];
cout << temp << " ";
iterStart = result[0].second; //更新搜索起始位置,搜索剩下的字符串
}
return 0;
}