gpt4 book ai didi

c++ - 在 C++ 中使用 regex/boost 查找两个数字之间的数字

转载 作者:行者123 更新时间:2023-11-30 02:38:49 26 4
gpt4 key购买 nike

我觉得这是一个非常基本的问题,但我没有找到相关的帖子。如果您知道,请在下面链接。所以我要做的是查看一个字符串并以 2 为一组提取数字。

这是我的代码:

int main() {
string line = "P112233";
boost::regex e ("P([0-9]{2}[0-9]{2}[0-9]{2})");
boost::smatch match;

if (boost::regex_search(line, match, e))
{
boost::regex f("([0-9]{2})"); //finds 11
boost::smatch match2;
line = match[0];
if (boost::regex_search(line, match2, f))
{
float number1 = boost::lexical_cast<float>(match2[0]);
cout << number1 << endl; // this works and prints out 11.
}

boost::regex g(" "); // here I want it to find the 22
boost::smatch match3;
if (boost::regex_search(line, match3, g))
{
float number2 = boost::lexical_cast<float>(match3[0]);
cout << number2 << endl;
}
boost::regex h(" "); // here I want it to find the 33
boost::smatch match4;
if (boost::regex_search(line, match4, h))
{
float number3 = boost::lexical_cast<float>(match4[0]);
cout << number3 << endl;
}
}
else
cout << "found nothing"<< endl;
return 0;
}

我能够得到第一个数字,但我不知道如何得到第二个 (22) 和第三个 (33)。我需要使用什么正确的表达方式?

最佳答案

正如@Cornstalks 提到的,您需要使用 3 个捕获组,然后您可以像这样访问它们:

int main() 
{
std::string line = "P112233";
boost::regex e("P([0-9]{2})([0-9]{2})([0-9]{2})");
boost::smatch match;

if (boost::regex_search(line, match, e))
{
std::cout << match[0] << std::endl; // prints the whole string
std::cout << match[1] << ", " << match[2] << ", " << match[3] << std::endl;
}

return 0;
}

输出:

P112233
11, 22, 33

关于c++ - 在 C++ 中使用 regex/boost 查找两个数字之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com