c++ - 如何访问 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]);
}
}
然而它显然不起作用。我已经研究过,当我访问smatch
using时[]
,它返回一个sub_match,除非构造函数,否则它没有公共成员。
如何将ip地址匹配的每一部分转换为一个字节?
最重要的是,std::cout << ipv4Match[0]
如果它不能访问内部的字符串,它怎么能工作,ipv4Match
因为它是一个sub_match
?
解决方案
您的问题与正则表达式无关,而是与字符串到 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());
推荐阅读
- python - 使用 POST 请求发送 XML
- php - 在 codeigniter 4 上重定向到 localhost:8080
- sql-server - 如何对没有任何渐进字段的表进行分区?
- c - pthreads_create 无明显原因导致段错误
- reactjs - Reactjs:使用默认路由嵌套多个路由
- css - 如何让哈巴狗 MIXIN “显示 flex”?
- python - 更新全局变量 pytest
- android - 苹果设备检查与 Firebase 应用检查的使用
- c++ - 如何拥有 QMap 的 QVector
- javascript - 重新安装 discord.js 时组合流脚本出错