C++正則表達式筆記
阿新 • • 發佈:2019-02-17
遍歷 gin str c++ iterator end long long 所有 out
C++11中引入了正則表達式庫
常用的3個接口:
1.regex_match,完全匹配
示例1:
#include <iostream> #include <regex> int main() { std::string text = "long long ago"; std::string text2 = "long long"; std::regex re(".+ng"); std::cout << std::boolalpha << std::regex_match(text, re) << std::endl; //false std::cout << std::regex_match(text2, re) << std::endl; //true std::system("pause"); return 0; }
示例1中匹配模式為.+ng,因為采用完全匹配,所以僅當目標文本以ng結尾才返回true
2.regex_search,在目標文本中進行搜索
示例2:
#include <iostream> #include <regex> int main() { using namespace std; string text = "I‘m 25."; string text2 = "I am 25 years old."; regex re("[0-9]+"); smatch sm; if (regex_search(text, sm, re)) { cout << sm[0] << endl; } if (regex_search(text2, sm, re)) { cout << sm[0] << endl; } system("pause"); return0; }
3.sregex_iterator,用於遍歷所有匹配
示例3:
#include <iostream> #include <string> #include <regex> int main() { using namespace std; string text = "I‘m 25. And my friend Bush is 24 years old."; regex re("[0-9]+"); sregex_iterator itr1(text.begin(), text.end(), re); sregex_iterator itr2; for (sregex_iterator itr = itr1; itr != itr2; ++itr) { smatch sm = *itr; cout << sm[0].str() << endl; } system("pause"); return 0; }
C++正則表達式筆記