c++11中regex正則表示式示例簡述
阿新 • • 發佈:2020-01-07
regex庫中涉及到的主要型別有:
- 以std::string為代表的處理字串的型別(我們知道還有儲存wchar_t的wstring類、原生c式字串const char*等等,為了簡化處理僅介紹std::string型別相關的操作,當你把握住了regex的主脈絡之後,想使用其他的版本只要類比就可以)
- std::regex類,該型別需要一個代表正則表示式的字串和一個文法選項作為輸入,當文法選項不提供時預設為ECMAScript。
- std::match_results類,該類用來記錄匹配的結果,這是一個模板類,該類的模板引數是一個迭代器型別,對於std::string來說我們定義了smatch作為match_results<string::const_iterator>作為別名。
- std::sub_match類,該類其實封裝了兩個迭代器,第一個代表開始部分,第二個代表結束部分,就像你用兩個下表索引去表達一個字串的某一個子串一樣。這個類就是通過這樣的方式提供原字串的某一個子串作為結果。實際上match_results中就封裝了一些std::sub_match型別的物件。(為什麼是一些而不是一個,因為一次匹配可能會產生多個結果返回,regex認為每個括號對構成一個子匹配項,regex匹配的結果可以顯式每個子匹配項匹配到的內容。)
- 現在我們有了表達字串的類,表達正則匹配的類,表達匹配結果的類,接下來regex提供三個匹配函式:
bool std::regex_match(...) bool std::regex_search(...) string std::regex_replace(...)//實際上返回型別是根據你輸入的資料型別對應的basic_string類。
首先說明三個函式功能上的不同,std::regex_match是全文匹配,即它希望你輸入的字串要和正則表示式全部匹配,才認為匹配成功,否則匹配失敗,而std::regex_search是在你輸入的字串中不斷搜尋符合正則表示式描述的子字串,然後將第一個匹配到的子字串返回。std::regex_replace是在std::regex_search的基礎上更進一步,可以將匹配的子字串替換為你提供的字串。
看幾個例子:
#include <iostream> #include <string> #include <regex> int main() { std::regex pattern("\\d{4}"); std::string content("hello_2018"); std::smatch result; if (std::regex_match(content,result,pattern)) { std::cout << result[0]; } system("pause"); return 0; }
匹配失敗,什麼都不會輸出。
這裡說明一下為什麼輸出的是result[0],其實result[0]返回的就是一個sub_match型別的物件。regex中認為正則表示式的每個括號對構成一個子匹配項,並認為整個字串作為0號子匹配項,然後根據左括號出現的位置,從1號開始編號,因此返回的result[0]就是匹配整個正則表示式的字串。
#include <iostream> #include <string> #include <regex> int main() { std::regex pattern("\\d{4}"); std::string content("hello_2018 by_2017"); std::smatch result; if (std::regex_search(content,pattern)) { std::cout << result[0]; } system("pause"); return 0; }
搜尋到第一個符合正則表示式的子串,輸出 2018。
#include <iostream> #include <string> #include <regex> int main() { std::regex pattern("\\d{4}"); std::string content("hello_2018 by_2017"); std::smatch result; auto begin = content.cbegin(); auto end = content.cend(); while (std::regex_search(begin,end,pattern)) { std::cout << result[0] << " "; begin = result[0].second; } system("pause"); return 0; }
用上述方式可以輸出字串中所有符合正則表示式匹配要求的字串,輸出 2018 2017。
#include <iostream> #include <string> #include <regex> int main() { std::regex pattern("\\d{4}"); std::string content("hello_2018 by_2017"); std::string result = std::regex_replace(content,pattern,"everyone"); std::cout << result; system("pause"); return 0; }
輸出 hello_everyone by_everyone。
以上就是c++11提供的regex模組的主要脈絡,其餘的關於對const char* 、wcahr_t型別的支援,以及regex_iterator、regex_token_iterator等迭代器的使用,以及掌控正則表示式行為方式的syntax_option_type的詳細內容,等你需要去了解的時候去看官網的詳解,相信學起來並不難。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。