首页 > 解决方案 > 如何访问 std::sub_match 中的正则表达式搜索结果?

问题描述

std::smatch ipv4Match;
std::regex_match(ipv4, ipv4Match, ip);

if (ipv4Match.empty())
{
    return std::nullopt;
}
else
{
    if (!ipv4Match.empty())
    {
        uint8_t a, b, c, d;
        a = (uint8_t)(ipv4Match[0]);
        b = (uint8_t)(ipv4Match[1]);
        c = (uint8_t)(ipv4Match[2]);
        d = (uint8_t)(ipv4Match[3]);
   }
}

然而它显然不起作用。我已经研究过,当我访问smatchusing时[],它返回一个sub_match,除非构造函数,否则它没有公共成员。

如何将ip地址匹配的每一部分转换为一个字节?

最重要的是,std::cout << ipv4Match[0]如果它不能访问内部的字符串,它怎么能工作,ipv4Match因为它是一个sub_match

标签: c++regexstd

解决方案


您的问题与正则表达式无关,而是与字符串到 int 的转换无关。

您可以使用std::atoi/ std::stoi

uint8_t a = std::stoi(ipv4Match[1].str());
uint8_t b = std::stoi(ipv4Match[2].str());
uint8_t c = std::stoi(ipv4Match[3].str());
uint8_t d = std::stoi(ipv4Match[4].str());

推荐阅读