boost中regex的使用

2022-08-09 14:21:13 字數 1268 閱讀 7087

boost是對stl的補充,regex是其中乙個模組。各方法類別很多,本文記錄常用方法。

引入標頭檔案

1. regex_match

regex reg("\\d");

string str = "123";

bool b = regex_match(str,reg);

2.regex_replace(string s, regex e, string t),把s中匹配了e的子串替換為t

regex reg("(colo)(u)(r)",boost::regex::icase|boost::regex::perl);

string s="colour,colour,color,colourize";

s=regex_replace(s,reg,"$1$3");

t中的$n代表reg中的第n個括號裡的內容,$3表示r,$1表示colo。上段**表示把colour換成color,boost::regex::icase/boost::regex::perl是標誌開關,表示忽略大小寫。可以把需要的標誌開關開啟,不需要時預設關閉。

regex_replace不修改原字串,而是生成乙個新串返回

3.erase_all_regex(string, regex),(boost::algorithm::erase_all_regex,in header ),刪除滿足regex的所有子串,它是在原串中直接修改

#include erase_all_regex(str, boost::regex("[\n|\t|\r]"))
刪除字串str中的所有空格

4.split_regex(序列式容器, string, regex),(),分割符為regex格式,分割string,將結果存放在容器中

#include vectorfields;

split_regex( fields, str, boost::regex("[\\*|x]"));

如果str = "5*6",fields中存放的是5和6。str不會被修改。

5.split(序列式容器,string,predicate), ()。

#include #include vectorresult;

split(result, school_code, is_any_of(";"));

is_any_of,用於判斷school_code中是否包含";",以;分割school_code存放在result中,不修改原串。

boost 正規表示式 regex

如果在引用boost regex出現連線錯誤,但是引用其他的庫卻沒有這個錯誤,這是因為對於boost來說,是免編譯的,但是,正則這個庫 是需要單獨編譯和使用的。簡單的辦法就是 直接將boost庫全部編譯,然後 找到正則的lib,編譯時候引用進去。include include include inc...

Regex類的使用。

regex類包括ismatch match matches replace 和 split 等方法。如果使用 和 封閉標記,則指示整個字串 而不只是子字串 都必須匹配正規表示式。1.match方法進行字串的匹配。string input test sina.com 待匹配的輸入串 string pa...

VC6 0下編譯boost庫的regex

今天要用到正規表示式,用網上的方法,直接使用命令 nmake vc6.mak 提示 nmake 不是內部或外部命令,也不是可執行的程式 上網搜尋了一下,說執行命令 call c program files microsoft visual studio vc98 bin vcvars32.bat 重...