gpt4 book ai didi

c++ - Boost C++ 正则表达式 - 如何返回所有匹配项

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:30 30 4
gpt4 key购买 nike

我有字符串 "SolutionAN ANANANA SolutionBN"我想返回所有以 Solution 开头的字符串并以 N 结尾.

使用正则表达式时 boost::regex regex("Solu(.*)N");我得到的输出为 SolutionAN ANANANA SolutionBN .

虽然我想以SolutionAN的身份离开和 SolutionBN .我是正则表达式的新手,我们将不胜感激。我正在使用的代码片段

#include <boost/regex.hpp>
#include <iostream>

int main(int ac,char* av[])
{
std::string strTotal("SolutionAN ANANANA SolutionBN");
boost::regex regex("Solu(.*)N");

boost::sregex_token_iterator iter(strTotal.begin(), strTotal.end(), regex, 0);
boost::sregex_token_iterator end;

for( ; iter != end; ++iter ) {
std::cout<<*iter<<std::endl;
}
}

最佳答案

问题是 * 是贪婪的。更改为使用非贪婪版本(注意 ?):

int main(int ac,char* av[])
{
std::string strTotal("SolutionAN ANANANA SolutionBN");
boost::regex regex("Solu(.*?)N");

boost::sregex_token_iterator iter(strTotal.begin(), strTotal.end(), regex, 0);
boost::sregex_token_iterator end;

for( ; iter != end; ++iter ) {
std::cout<<*iter<<std::endl;
}
}

关于c++ - Boost C++ 正则表达式 - 如何返回所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16665981/

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