gpt4 book ai didi

c++ - 在 C++ 中使用正则表达式查找 [/和] 之间的数字

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:04 25 4
gpt4 key购买 nike

我想找到 [/] 之间的数字(在本例中为 12345)。

我写过这样的代码:

float num;
string line = "A111[/12345]";
boost::regex e ("[/([0-9]{5})]");
boost::smatch match;
if (boost::regex_search(line, match, e))
{
std::string s1(match[1].first, match[1].second);
num = boost::lexical_cast<float>(s1); //convert to float
cout << num << endl;
}

但是,我收到此错误:解析正则表达式片段时发生错误:'/([0-9]{5}>>>HERE>>>)]'。

最佳答案

您需要对正则表达式中表示 character classes 的特殊字符 [] 进行双重转义.正确的正则表达式声明将是

boost::regex e ("\\[/([0-9]{5})\\]");

这是必要的,因为 C++ 编译器还使用反斜杠来转义 \n 等实体,而正则表达式引擎使用反斜杠来转义特殊字符,以便将它们视为文字。因此,反斜杠加倍。当您需要匹配文字反斜杠时,您将不得不使用其中的 4 个(即 \\\\)。

关于c++ - 在 C++ 中使用正则表达式查找 [/和] 之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734086/

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