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;
}
相关推荐
轻松Ai享生活1 小时前
5 节课深入学习Linux Cgroups
linux
christine-rr1 小时前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神5552 小时前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆2 小时前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
乌萨奇也要立志学C++2 小时前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
小莞尔3 小时前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔3 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329293 小时前
Day03_刷题niuke20250915
c语言
獭.獭.4 小时前
Linux -- 信号【上】
linux·运维·服务器
hashiqimiya4 小时前
centos配置环境变量jdk
linux·运维·centos