#include


 

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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM