C语言正则表达式实例

版本一

多次解析出错

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(&reg, 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(&reg, 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(&reg);                                     
    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;
}
相关推荐
码农客栈1 小时前
linux 交叉编译tslib
linux
是隼人1 小时前
buuctf-pwn [NewStarCTF 2023 公开赛道]stack migration(64位栈迁移)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
鱼月半1 小时前
两台电脑直连网络不通怎么办?
linux·网络协议
光电笑映2 小时前
网络通信基础:从协议分层到 Socket 编程预备
linux·运维·服务器·网络
酸菜。3 小时前
dw_apb_gpio总结
linux
wunaiqiezixin3 小时前
MIT 6.S081 file system 实验篇(lab9):Large files (moderate)
linux·unix·os·xv6·mit6.s081
GeW3 小时前
RHCE 考试通过率提升:核心考点、实验环境与排错技巧
linux
吴声子夜歌4 小时前
Shell编程实例——与解析相关的任务(二)
linux·运维·shell
mengge.cloud4 小时前
0917Docker 小白实验教程(理论+实操)
linux·服务器·网络·docker
Logic1014 小时前
C语言/数据结构贪心算法题解:买卖股票的最佳时机——一次交易最大利润(O(n)时间O(1)空间)
c语言·数据结构·贪心算法·数组·时间复杂度·算法题·股票交易