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;
}
相关推荐
小灰灰搞电子27 分钟前
C语言 <ctype.h> 头文件详解
c语言·ctype.h
阿钱真强道1 小时前
17 嵌入式操作系统 | uloop 事件循环:TCP 客户端
c语言·tcp/ip·tcp·事件循环·uloop
谷哥的小弟1 小时前
CentOS Stream浴火重生
linux·运维·centos
程序员-Benothing2 小时前
Shell输入输出详解:read、echo、printf、颜色输出
linux·运维·服务器
FPGA小徐3 小时前
从 NEMU 到 AbstractMachine:程序、运行时环境与 AM 完全解析
linux·运维·服务器
会员果汁3 小时前
函数调用和变长参数
c语言
qetfw4 小时前
Debian Chrony 时间同步、RAID5 与 LUKS 磁盘加密配置
linux·debian
白山编程大哥6 小时前
Lua 中使用 C 语言的用户自定义类型——userdata
c语言·junit·lua
东城居士6 小时前
Linux驱动阻塞与非阻塞访问的理解
linux·嵌入式系统
无敌贵点大王6 小时前
RTThread学习记录13——关于要使用一个外设,RTThread与cubemx到底要怎么配合?
c语言·stm32·学习·rtthread