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

如何用C++正则表达式匹配字符串中的固定位置?

C++正则表达式是否支持引用字符串内的固定位置?

C++标准库提供的正则表达式(遵循ECMAScript规范)不支持你示例中虚构的@n这类直接引用字符串固定索引位置的语法。

针对你的需求——先匹配[a-z]+[0-9]+,再从字符串的第7个字符位置开始截取剩余内容,由于无法提前知晓[a-z]+和[0-9]+的匹配长度,你可以通过两步操作实现:

  1. 先用正则提取第一个匹配分组;
  2. 结合字符串的固定索引位置,手动截取后续内容。

示例代码如下:

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

int main() {
    std::string target = "hello12345";
    std::regex pattern(R"(([a-z]+[0-9]+))");
    std::smatch result;

    if (std::regex_search(target, result, pattern)) {
        std::string first_match = result[1].str();
        // 按示例需求,从索引7的位置开始截取剩余内容
        if (target.size() > 7) {
            std::string second_part = target.substr(7);
            std::cout << "Match: [\"" << first_match << "\", \"" << second_part << "\"]" << std::endl;
        }
    }
    return 0;
}

如果你的场景有更复杂的正则匹配逻辑,C++原生正则也无法实现基于全局字符串索引的内部定位,必须拆分正则匹配与字符串截取的步骤来完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:22:06