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"); return 0; }
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; }
P.S.
目前没找到regex的标准发音,我将它读作“rej-eks”。参考链接:What is the correct way to pronounce "regex"?