You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将正则表达式匹配结果转换为C++的Duration结构体?

问题描述
  • 正则表达式:([0-9]*)|([0-9]*\.[0-9]*)
  • 目标字符串:word1 word2 0:12:13.23456(示例)
  • 期望匹配结果:0、12、13.23456

需求

将上述匹配结果映射到以下C++结构体:

struct Duration {
    unsigned int hours;
    unsigned int minutes;
    double seconds;
};

当前代码

现有正则匹配代码如下,需补充匹配结果到结构体成员的赋值逻辑:

Duration duration;
std::regex regex("([0-9]*):([0-9]*):([0-9]*.[0-9]*)");
auto begin = std::sregex_iterator(data.begin(), data.end(), regex); // data是std::string实例
auto end = std::sregex_iterator();
for (auto it = begin; it != end; it++) {
    auto match = *it;
    // 如何遍历并赋值给Duration实例的各个成员?
}

解决方案

你当前使用的正则已经精准捕获了时分秒三个分组,直接通过std::smatch的分组索引提取值并转换类型即可完成赋值:

Duration duration;
// 用原始字符串字面量避免转义麻烦,同时修正点号的转义(.需转义为\.才能匹配实际小数点)
std::regex regex(R"(([0-9]*):([0-9]*):([0-9]*\.[0-9]*))");
auto begin = std::sregex_iterator(data.begin(), data.end(), regex);
auto end = std::sregex_iterator();

for (auto it = begin; it != end; ++it) {
    std::smatch match = *it;
    // 分组0是整个匹配串,1-3分别对应小时、分钟、秒的捕获结果
    if (match.size() == 4) {
        // 字符串转unsigned int,用stoul比stoi更适配无符号类型
        duration.hours = std::stoul(match[1].str());
        duration.minutes = std::stoul(match[2].str());
        // 字符串转double处理带小数的秒数
        duration.seconds = std::stod(match[3].str());
    }
}

关键注意点

  1. 正则中的小数点必须转义为\.,否则会匹配任意字符;使用C++原始字符串R"(...)"可以省去额外的转义符,提升可读性。
  2. 转换字符串时,stoul(字符串转无符号长整型)更适合unsigned int成员,避免溢出风险;stod专门用于转换带小数的数值。
  3. 先判断match.size()是否为4,确保三个捕获分组都有效,避免越界访问。

内容的提问来源于stack exchange,提问作者justanotherguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:06:21