码迷,mamicode.com
首页 > 其他好文 > 详细

#include <boost/regex.hpp>

时间:2016-08-14 11:29:43      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

 

boost C++的正则表达式库boost.regex可以应用正则表达式于C++。正则表达式大大减轻了搜索特定模式字符串的负担,在很多语言中都是强大的功能。

 

boost.regex库中两个最重要的类是boost::regex和boost::smatch,它们都在boost/regex.hpp文件中定义。前者用于定义一个正则表达式,而后者可以保存搜索结果。

 

小结:C++的正则表达式库早已有之,但始终没有哪个库纳入到标准化流程中。目前该库已经顺利的成立新一代C++标准库中的一员,结束了C++没有标准正则表达式支持的时代。

 

1 boost::regex_match

正则表达式匹配

2 boost::regex_replace

正则表达式替换

3 boost::regex_search

正则表达式检索

 

 1 #include <iostream>
 2 #include <boost/regex.hpp>
 3 
 4 void main()
 5 {
 6     std::string str = "chinaen 8Glish";
 7 
 8     boost::regex expr("(\\w+)\\s(\\w+)");
 9 
10     //+ 用来表示重复一或多次
11     //d-digit 任何0-9之间的数字
12     //s-space 任何空格字符
13     //u-upper A-Z之间的大写字母。如果设置了地域的话,可能包含其他字符
14     //w-word 任何单词字符-字母数字下划线
15 
16     std::cout << boost::regex_match(str, expr) << std::endl;//匹配1,不匹配0
17 
18     boost::smatch what;
19 
20     if (boost::regex_search(str, what, expr))//正则表达式检索
21     {
22         std::cout << what[0] << std::endl;
23         std::cout << what[1] << std::endl;
24         std::cout << what[2] << std::endl;
25         std::cout << what[3] << std::endl;
26     }
27     else
28     {
29         std::cout << "检索失败" << std::endl;
30     }
31 }

 

boost::regex_replace

正则表达式替换

//s-space 任何空格字符

 

 1 #include <iostream>
 2 #include <boost/regex.hpp>
 3 
 4 void main()
 5 {
 6     std::string str = "chinaen 8Glish";
 7 
 8     boost::regex expr("\\s");//s-space 任何空格字符
 9 
10     std::string tihuan = "____";
11 
12     std::cout << boost::regex_replace(str, expr, tihuan) << std::endl;//把expr替换
13 }

 

#include <boost/regex.hpp>

标签:

原文地址:http://www.cnblogs.com/denggelin/p/5769624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!