Welcome

首页 / 软件开发 / C++ / C++中正则表达式(regex) 替换(replace) 详解

C++中正则表达式(regex) 替换(replace) 详解2014-11-20正则表达式, 可以替换(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.1800Caroline 201.555.2368 862-55-0123201.555.2368
作者:csdn博客 Spike_King