如何访问 std::sub_match 内的正则表达式搜索结果?
How to access regex search result inside 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
时,它 returns 一个 sub_match,它没有 public 成员,除非构造函数。
如何将匹配的ip地址的每一部分转换成一个字节?
最重要的是,如果 std::cout << ipv4Match[0]
无法访问 ipv4Match
中的内部字符串,因为它是 sub_match
,它如何工作?
您的问题与正则表达式无关,而是字符串到整数的转换。
您可以使用 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());
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
时,它 returns 一个 sub_match,它没有 public 成员,除非构造函数。
如何将匹配的ip地址的每一部分转换成一个字节?
最重要的是,如果 std::cout << ipv4Match[0]
无法访问 ipv4Match
中的内部字符串,因为它是 sub_match
,它如何工作?
您的问题与正则表达式无关,而是字符串到整数的转换。
您可以使用 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());