C++ 匹配并提取包括加中括号的日期时间的正则表达式

在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."。

相关推荐
saltymilk12 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥13 小时前
C++ lambda 匿名函数
c++
沐怡旸19 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥19 小时前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++