C++-正则表达式(regex)替换(replace)的详解及代码正则表达式(regex) 替换(replace) 的详解及代码
本⽂地址: blog.csdn/caroline_wendy/article/details/17321639
正则表达式, 可以替换(replace)匹配的字符串, 使⽤regex_replace()函数, 需要指定替换的格式;
也可以提供参数, 进⾏特定的输出, 替换格式的命名空间: "boost::regex_constants::"
编程环境: gcc 4.8.1 + eclipse cdt + 11 + boost
代码:
输出:[cpp]
01. #include <iostream>
02. #include <string>
03.
04. #include <boost/regex.hpp>
05.
06. using namespace std;
07. using namespace boost;
08.
09. int main()
10. {
11. //问号(?)表⽰之前的可以选择
12. std::string phone =
13. "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ]?)(\\d{4})";
14. boost::regex r(phone);
15. //代替
regex匹配
16. std::string fmt("$2.$5.$7");
17. std::string number("(908)555-1800");
18. std::cout << regex_replace(number, r, fmt) << std::endl;
19.
20. std::string file("Caroline (201)555-2368 862-55-0123");
21. std::cout << boost::regex_replace(file, r, fmt) << std::endl;
22. std::cout << boost::regex_replace(file, r, fmt,
23. boost::regex_constants::format_no_copy) << std::endl;
24. }
[plain]
01. 908.555.1800
02. Caroline 201.555.2368 862-55-0123
03. 201.555.2368
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论