regex庫中涉及到的主要類型有:ios
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的基礎上更進一步,能夠將匹配的子字符串替換爲你提供的字符串。c++
看幾個例子:正則表達式
#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, result, pattern)) { std::cout << result[0]; } system("pause"); return 0; }
搜索到第一個符合正則表達式的子串,輸出 2018。c++11
#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, result, pattern)) { std::cout << result[0] << " "; begin = result[0].second; } system("pause"); return 0; }
用上述方式能夠輸出字符串中全部符合正則表達式匹配要求的字符串,輸出 2018 2017。code
#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的詳細內容,等你須要去了解的時候去看官網的詳解,相信學起來並不難。索引