2012-07-04 11 views
9

我有這些變量:如何使用Boost正則表達式替換方法?

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. 

我只想只替換了它的第一次出現。

謝謝夥計們。

編輯:我發現這一點:

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

,但它說,該函數不存在,我猜的參數是此刻不正確。

+0

它不是一個有效的函數。 –

回答

29

這是基本用法的例子:

#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; 
} 

輸出

hellooooooooo

你好鮑勃

確保您包括<boost/regex.hpp>並鏈接到boost_regex庫。