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

C++如何使用正则匹配从目标字符串提取fetID、ProID后缀数字

C++实现正则提取指定ID后缀数字

待处理的原始字符串为:

ABC HHHH fetID_3141 ProID_1045

需要提取fetID_3141、ProID_1045两个字段中下划线后的数字,即3141、1045。

实现方案

直接使用C++11标准引入的标准正则库<regex>即可完成提取,不需要引入第三方依赖。
正则匹配规则设计为(fetID|ProID)_(\d+):

  • 第一组捕获匹配ID前缀(fetID/ProID)
  • 第二组捕获匹配下划线后的连续数字,也就是我们需要的目标内容

完整可运行代码如下:

#include <iostream>
#include <string>
#include <regex>
#include <vector>

int main() {
    // 待处理原始字符串
    std::string raw_str = "ABC HHHH fetID_3141 ProID_1045";
    // 定义正则规则,使用原始字符串避免转义符冲突
    std::regex pattern(R"((fetID|ProID)_(\d+))");
    std::vector<int> res;

    // 遍历字符串中所有匹配结果
    auto match_begin = std::sregex_iterator(raw_str.begin(), raw_str.end(), pattern);
    auto match_end = std::sregex_iterator();
    for (auto i = match_begin; i != match_end; ++i) {
        std::smatch match = *i;
        // 第2个捕获组是数字字符串,转int存入结果集
        int num = std::stoi(match[2].str());
        res.push_back(num);
    }

    // 输出验证结果
    for (int n : res) {
        std::cout << n << std::endl;
    }
    return 0;
}

运行后输出结果为:

3141
1045

注意事项

  • 编译时需要开启C++11及以上标准支持,gcc编译可加参数-std=c++11
  • 低于GCC 5版本的编译器对std::regex支持不完善,建议使用更高版本编译器或VS2015及以上的MSVC编译器
  • 如果后续需要新增提取其他同格式ID,只需要在正则的前缀分组里用|分隔新增前缀即可,比如要提取xxxID_123就把规则改成(fetID|ProID|xxxID)_(\d+)
  • 正则捕获组索引从1开始,索引0存储的是当前匹配到的完整字符串,不要取错位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:18:28