C++ 如何使用Boost正则表达式替换方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11321533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:02:17  来源:igfitidea点击:

how to use Boost regular expression replace method?

c++boostboost-regex

提问by unwise guy

I have these variables:

我有这些变量:

boost::regex re //regular expression to use
std::string stringToChange //replace this string
std::string newValue //new value that is going to replace the stringToChange depending on the regex.

I only want to replace the first occurrence of it only.

我只想替换它的第一次出现。

Thanks fellas.

谢谢各位。

EDIT: I've found this:

编辑:我发现了这个:

boost::regex_replace(stringToChange, re, boost::format_first_only);

but it says the function does not exists, I'm guessing the parameters are incorrect at the moment.

但它说该函数不存在,我猜目前参数不正确。

回答by Jesse Good

Here is an example of basic usage:

下面是一个基本用法的例子:

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

int main(){
  std::string str = "hellooooooooo";
  std::string newtext = "o Bob";
  boost::regex re("ooooooooo");
  std::cout << str << std::endl;

  std::string result = boost::regex_replace(str, re, newtext);
  std::cout << result << std::endl;
}

Output

输出

hellooooooooo

hello Bob

你好哦哦哦

你好鲍勃

Make sure you are including <boost/regex.hpp>and have linked to the boost_regex library.

确保您包含<boost/regex.hpp>并链接到 boost_regex 库。