C++中正则表达式(regex) 替换(replace) 详解
正则表达式, 可以替换(replace)匹配的字符串, 利用regex_replace()函数, 需要指定替换的名目;
也可以提供参数, 举办特定的输出, 替换名目标定名空间: "boost::regex_constants::"
编程情况: gcc 4.8.1 + eclipse cdt + c++11 + boost
代码:
#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main()
{
//问号(?)暗示之前的可以选择
std::string phone =
"(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ]?)(\\d{4})";
boost::regex r(phone);
//取代
std::string fmt("$2.$5.$7");
std::string number("(908)555-1800");
std::cout << regex_replace(number, r, fmt) << std::endl;
std::string file("Caroline (201)555-2368 862-55-0123");
std::cout << boost::regex_replace(file, r, fmt) << std::endl;
std::cout << boost::regex_replace(file, r, fmt,
boost::regex_constants::format_no_copy) << std::endl;
}
输出:
908.555.1800 Caroline 201.555.2368 862-55-0123 201.555.2368
作者:csdn博客 Spike_King