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

相关推荐
落羽的落羽1 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
闻缺陷则喜何志丹2 小时前
【Assimp】三维模型读取库
c++·算法·assimp·三维模型库
小飞在努力2 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
炸薯条!3 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
CappuccinoRose3 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
tryCbest3 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
-梅4 小时前
linux(番外)线程,锁,条件变量封装;日志与线程池
linux·c语言·前端·c++
S_WEAN4 小时前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
词却4 小时前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
星落梦生5 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript