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;
}
相关推荐
2301_789015627 分钟前
C++:二叉搜索树
c语言·开发语言·数据结构·c++·算法·排序算法
kaoa0001 小时前
Linux入门攻坚——58、varnish入门
linux·运维·服务器
SystickInt8 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
CS Beginner8 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
烛阴8 小时前
C# 正则表达式(2):Regex 基础语法与常用 API 全解析
前端·正则表达式·c#
JAY_LIN——88 小时前
指针-数组
c语言·排序算法
Xの哲學8 小时前
Linux流量控制: 内核队列的深度剖析
linux·服务器·算法·架构·边缘计算
tuokuac9 小时前
docker中nginx配置报错解决
linux·运维·服务器
Zeku9 小时前
20251129 - 详细解析Linux的mmap(内存映射)
linux·驱动开发·嵌入式软件·linux应用开发
进阶的猪9 小时前
STM32 使用HAL库SPI读写FLASH(W25Q128JV)数据 Q&A
c语言·stm32·单片机