当前位置: 首页> 游戏> 攻略 > C++ 匹配并提取包括加中括号的日期时间的正则表达式

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

时间:2025/7/9 8:07:26来源:https://blog.csdn.net/m0_54901781/article/details/140442504 浏览次数:0次

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: