【问题标题】:How to access regex search result inside std::sub_match?如何访问 std::sub_match 中的正则表达式搜索结果?
【发布时间】:2020-08-25 03:29:15
【问题描述】:
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]);
   }
}

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

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

最重要的是,如果std::cout << ipv4Match[0] 无法访问ipv4Match 内的内部字符串,因为它是sub_match,它如何工作?

【问题讨论】:

标签: c++ regex std


【解决方案1】:

您的问题与正则表达式无关,而是字符串到 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());

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2022-11-26
    • 2015-12-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多