正则表达式(regex) 替换(replace) 的 详解 及 代码
本文地址: http://blog.csdn.NET/caroline_wendy/article/details/17321639
正则表达式, 可以替换(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