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

相关推荐
cici1587421 小时前
基于C#的智能仓储上位机系统实现方案
开发语言·c#
-Try hard-21 小时前
线程间通信 | 避免资源竞争、实现同步通信
linux·开发语言·信息与通信
楼田莉子21 小时前
C++并发库介绍(上)
开发语言·c++·学习
Nightmare00421 小时前
切换conda环境的时候输出zstandard could not be imported. Running without .conda support.
开发语言·python·conda
Trouvaille ~21 小时前
【项目篇】从零手写高并发服务器(一):项目介绍与开发环境搭建
linux·运维·服务器·网络·c++·高并发·muduo库
weixin_3954489121 小时前
build_fsd_luyan_from_rm——注释
开发语言·windows·python
lsx20240621 小时前
NumPy 算术函数
开发语言
程序员南飞21 小时前
算法笔试-求一个字符串的所有子串
java·开发语言·数据结构·python·算法·排序算法
秦jh_21 小时前
【C++】哈希扩展
开发语言·c++·哈希算法
开发者小天21 小时前
python中使用jupyter notebook 绘制正态分布直方图 密度图 小提琴图 模仿企鹅喙长分布图
开发语言·python·jupyter