C++ regex 函数主要有三个,具体可以参考文档 https://cplusplus.com/reference/regex/
- regex_match
- regex_search
- regex_replace
性能
如果有性能要求,使用 boost regex 会快很多。
regex
在使用正则匹配前,需要先定义正则表达式,一般使用 std::regex
,它由模板 basic_regex 实例化而来:
typedef basic_regex<char> regex;
match results
部分操作会返回匹配结果,一般可以保存在 std::cmatch
或 std::smatch
, 它由模板 match_results 实例化而来:
typedef match_results<const char*> cmatch;
typedef match_results<string::const_iterator> smatch;
匹配成功后,match_results 会包含多个 sub_match 对象,第一个元素是整个匹配段,而之后的每个元素分别是正则表达式的匹配项。
regex_match
检查目标序列与正则表达式是否匹配,返回bool;可以同时将匹配结果保存在 match_results 中。
示例
匹配日期,格式:2023-02-21 15:45:23,2023/02/21 15:45:23
#include <iostream> #include <regex> std::regex pattern(R"((\d{4})[-/](\d{2})[-/](\d{2}) (\d{2}):(\d{2}):(\d{2}))"); long str_to_time(const char* s) { std::cmatch m; if (!std::regex_match(s, m, pattern) || m.size() != 7) { return 0; } int year = std::stoi(m[1]); int mon = std::stoi(m[2]); int day = std::stoi(m[3]); int hour = std::stoi(m[4]); int min = std::stoi(m[5]); int sec = std::stoi(m[6]); std::tm t{ sec, min, hour, day, mon - 1, year - 1900, 0, 0, 0, }; return mktime(&t); } int main() { std::cout << str_to_time("2023-02-21 15:23:46") << std::endl; std::cout << str_to_time("2023/02/21 15:23:46") << std::endl; }
Add Comment