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

相关推荐
阿让啊4 小时前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
liulilittle4 小时前
OPENPPP2 —— IP标准校验和算法深度剖析:从原理到SSE2优化实现
网络·c++·网络协议·tcp/ip·算法·ip·通信
honder试试7 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky7 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
田里的水稻7 小时前
C++_队列编码实例,从末端添加对象,同时把头部的对象剔除掉,中的队列长度为设置长度NUM_OBJ
java·c++·算法
ponnylv7 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人7 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
Jayden_Ruan8 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊8 小时前
启动文件Startup_vle.c
c语言·开发语言
liulun8 小时前
Skia如何渲染 Lottie 动画
c++·动画