C++ 替换匹配正则表达式片段的令牌

C++ 替换匹配正则表达式片段的令牌,c++,regex,c++11,boost,boost-regex,C++,Regex,C++11,Boost,Boost Regex,我想使用正则表达式作为搜索模式和构造字符串的模板。(我之所以使用boost::regex,是因为我在gcc 4.8.4中,其中显然不完全支持regex(直到4.9)): 也就是说,我想要构造一个正则表达式,将它传递给一个函数,使用正则表达式匹配一些文件,然后按照相同的模式构造一个输出文件名。例如: 正则表达式:“file.*\.txt” 匹配“file_1.txt”、“file_2.txt”等内容。 然后我想从中构造 输出:“file_all.txt” 也就是说,我想匹配以“file_u2;”开

我想使用正则表达式作为搜索模式和构造字符串的模板。(我之所以使用boost::regex,是因为我在gcc 4.8.4中,其中显然不完全支持regex(直到4.9)):

也就是说,我想要构造一个正则表达式,将它传递给一个函数,使用正则表达式匹配一些文件,然后按照相同的模式构造一个输出文件名。例如:

正则表达式:“file.*\.txt” 匹配“file_1.txt”、“file_2.txt”等内容。 然后我想从中构造 输出:“file_all.txt”

也就是说,我想匹配以“file_u2;”开头,以“.txt”结尾的文件,然后我想在“file_2;”和“.txt”之间填充“all”,所有这些都来自一个regex对象

我们将跳过与正则表达式的匹配,因为这很简单,但重点是替换:

#include <iostream>
#include <iterator>
#include <string>

#include <boost/regex.hpp>

std::string constructOutput(const boost::regex& myRegex)
{
    // How to replace the match to the center of the filenames here?
    // return boost::regex_replace(?, myRegex, "all");
}

int main()
{
   // We can do something like this, but it requires us to manually separate the "center" of the regex from the string, as well as keep around a string object and a regex object:
//   std::string myText = "File_.*.txt";
//   boost::regex myRegex("_.*\\.");

//   std::cout << '\n' << boost::regex_replace(myText, myRegex, "_all.") << '\n';

    // Want to do this:
    boost::regex myRegex("File_.*\\.txt");
    std::string outputString = constructOutput(myRegex);
    std::cout << outputString << std::endl;
}
#包括
#包括
#包括
#包括
std::string constructOutput(const boost::regex和myRegex)
{
//如何在此处替换与文件名中心的匹配?
//返回提升::regex_replace(?,myRegex,“all”);
}
int main()
{
//我们可以这样做,但它要求我们手动将正则表达式的“中心”与字符串分开,并保留字符串对象和正则表达式对象:
//std::string myText=“File.*.txt”;
//boost::regex myRegex(“.*\\”);

//std::cout如果文件名总是以“file_u”开头,以“.txt”结尾,而唯一更改的部分在这两者之间,并且您希望将其替换为“all”,为什么不将名称硬编码为“file_uall.txt”然后你不需要做任何替换。我认为你在描述问题时遗漏了一个重要的细节。@DarkFalcon说,然后我传递constructOutput“other-.*thing.txt”,并希望它构造“other allthing.txt”。所以我猜在本例中是“all”将被硬编码为替换,但我希望它替换正则表达式中的通配符部分。但为什么?问题是,如果您提前知道前缀和后缀,为什么不简单地连接字符串?@DarkFalcon我猜想法是在正则表达式上运行正则表达式,用特定的数字替换正则表达式匹配模式。我猜问题是您无法从regex对象获取原始字符串,因此我正在寻找解决方法。原始regex字符串可通过
basic\u string str()const;
basic\u regex
对象上获得。