在C++中,你可以使用std::regex
库来匹配包含日期和时间的字符串。以下是一个简单的例子,它展示了如何使用正则表达式来匹配形如[YYYY-MM-DD HH:MM:SS]
的字符串。include <iostream>
#include <string>
#include <regex>
int main() {
std::string text = "The event will happen on [2023-04-01 14:30:00].";
std::regex datetime_regex(R"(\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\])");
std::smatch matches;
if (std::regex_search(text, matches, datetime_regex) && matches.size() > 1) {
// 提取年、月、日、小时、分钟、秒
int year = std::stoi(matches[1].str());
int month = std::stoi(matches[2].str());
int day = std::stoi(matches[3].str());
int hour = std::stoi(matches[4].str());
int minute = std::stoi(matches[5].str());
int second = std::stoi(matches[6].str());
std::cout << "Year: " << year << std::endl;
std::cout << "Month: " << month << std::endl;
std::cout << "Day: " << day << std::endl;
std::cout << "Hour: " << hour << std::endl;
std::cout << "Minute: " << minute << std::endl;
std::cout << "Second: " << second << std::endl;
} else {
std::cout << "No datetime found." << std::endl;
}
return 0;
}
这段代码使用了std::regex_search
来搜索文本中符合正则表达式的部分,并且提取了年、月、日、小时、分钟和秒。如果找到匹配,它们将被转换为整数并输出。如果没有找到匹配,将输出"No datetime found."。