C++11引入了<regex>库,使用比较方便,不再需要boost等第三方库。文章简单介绍C++ regex正则表达式的使用。
C++ 正则表达式相关函数有3个:regex_match、 regex_search 和 regex_replace。
regex_match():判读是否匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <regex> int main(int argc, char* argv[]) { std::string str = "Hello World!"; // match是regex正则表达式对象 std::regex match("(Hel)(.*)"); // 匹配字符串以Hel开头,后可跟任意字符 if ( std::regex_match(str, match) ) std::cout << "字符串中有匹配 (Hel)(.*) \n"; if ( std::regex_match(str.begin(), str.end(), match) ) std::cout << "字符串中有匹配 (Hel)(.*) \n"; return 0; } |
regex_search():获得匹配的字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <regex> #include <string.h> int main(int argc, char* argv[]) { std::string str = "My first program is Hello World! oh"; std::regex r("Hel[a-zA-Z]+"); std::smatch m; // 存放匹配的字符串 std::regex_search(str, m, r); for (auto x : m) std::cout << x << std::endl; return 0; } |
regex_replace():替换匹配的字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <regex> #include <iterator> int main() { std::string str = "My first program is Hello World! oh yeah\n"; std::regex r("Hel[a-zA-z]+"); std::cout << std::regex_replace(str, r, "Fuck") << std::endl; // 或 std::string res; std::regex_replace(std::back_inserter(res), str.begin(), str.end(), r, "Fuck"); std::cout << res << std::endl; return 0; } |