gpt4 book ai didi

c++ - boost::regex 搜索和替换

转载 作者:行者123 更新时间:2023-11-28 05:00:42 33 4
gpt4 key购买 nike

我正在编写一个使用 boost::regex 进行字符串操作的程序.在所有情况下,我都需要 regex_search 的功能, 但只有特定情况需要 regex_replace .有没有一种方法可以将两者结合起来,这样替换 就不会重做搜索 的工作?

打完电话就知道了

boost::regex re;
std::string str, fmt;
// . . .
boost::smatch match;
regex_search( str, match, re );

match包含匹配的信息,但是

match.format( fmt );

不做什么

regex_replace( str, re, fmt );

会。

最佳答案

也许使用动态替换:C++ boost regex replace with conditions

The sample there has a c++03, c++11 variants with named/unnamed submatches.

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

int main() {
std::string pattern = "dddd, mmmm d, yyyy";
pattern = boost::regex_replace(pattern, boost::regex("(dddd)|(d)|(mmmm)|(yyyy)"), [](auto& match)->std::string{
if (match.str() == "dddd")
return "Tuesday";

if (match.str() == "d")
return "26";

if (match.str() == "mmmm")
return "December";

if (match.str() == "yyyy")
return "2016";

return "";
});

std::cout << "Result: " << pattern << "\n";
}

关于c++ - boost::regex 搜索和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46126665/

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