regex庫中涉及到的主要類型有:
bool std::regex_match(...)bool std::regex_search(...)string std::regex_replace(...)//實際上返回類型是根據(jù)你輸入的數(shù)據(jù)類型對應(yīng)的basic_string類。
首先說明三個函數(shù)功能上的不同,std::regex_match是全文匹配,即它希望你輸入的字符串要和正則表達式全部匹配,才認為匹配成功,否則匹配失敗,而std::regex_search是在你輸入的字符串中不斷搜索符合正則表達式描述的子字符串,然后將第一個匹配到的子字符串返回。std::regex_replace是在std::regex_search的基礎(chǔ)上更進一步,可以將匹配的子字符串替換為你提供的字符串。
看幾個例子:
#include <iostream>#include <string>#include <regex>int main() { std::regex pattern("http://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中認為正則表達式的每個括號對構(gòu)成一個子匹配項,并認為整個字符串作為0號子匹配項,然后根據(jù)左括號出現(xiàn)的位置,從1號開始編號,因此返回的result[0]就是匹配整個正則表達式的字符串。
#include <iostream>#include <string>#include <regex>int main() { std::regex pattern("http://d{4}"); std::string content("hello_2018 by_2017"); std::smatch result; if (std::regex_search(content, result, pattern)) { std::cout << result[0]; } system("pause"); return 0;}搜索到第一個符合正則表達式的子串,輸出 2018。
#include <iostream>#include <string>#include <regex>int main() { std::regex pattern("http://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, result, 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("http://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模塊的主要脈絡(luò),其余的關(guān)于對const char* 、wcahr_t類型的支持,以及regex_iterator、regex_token_iterator等迭代器的使用,以及掌控正則表達式行為方式的syntax_option_type的詳細內(nèi)容,等你需要去了解的時候去看官網(wǎng)的詳解,相信學(xué)起來并不難。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對武林網(wǎng)的支持。
新聞熱點
疑難解答