【字符串解析】IP地址字段解析提取函数接口

  在嵌入式业务逻辑中,我们有时需要从配置文件、串口或者服务端接收的消息数据中进行字符串解析,来提取需要的目标字符串字段。通常我们会调用字符串处理相关的函数,例如strstr,strchr,sscanf等,再结合指针偏移来提取目标字段。实现这种方式的前提是,我们需要提前知道字符串固定的格式内容,如果待解析的字符串内容或者格式偏差的情况,那么我们编写好的字符串解析处理程序就不太适用了。以下是一个通用的对于从字符串中解析IP地址的函数接口,只要字符串中有完整的IP地址字段就会被提取出来。以供参考。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>

#define OUT
#define IN

char extract_IPInfo(IN char *str, OUT char *ip)
{
    regex_t regex;
    regmatch_t pmatch[1];
    const char *pattern = "([0-9]{1,3}\\.){3}[0-9]{1,3}";
    int ret;

    // Compile the regular expression
    ret = regcomp(&regex, pattern, REG_EXTENDED);
    if (ret) {
        fprintf(stderr, "Could not compile regex\n");
        return 0;
    }

    // Execute the regular expression
    const char *p = str;
    while (regexec(&regex, p, 1, pmatch, 0) == 0) {
        // Extract the matched IP address
        int start = pmatch[0].rm_so;
        int end = pmatch[0].rm_eo;
        strncpy(ip, p + start, end - start);
        ip[end - start] = '\0';

        // Print the matched IP address
        printf("Found IP: %s\n", ip);

        // Move the pointer forward
        p += end;
    }

    // Free compiled regular expression
    regfree(&regex);
    return 1;
}

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值