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

如何用C++正则表达式提取#include语句中<>内的头文件名

提取C++ #include语句中<>内的头文件名

正则表达式设计

使用以下正则表达式可精准匹配#include <xxx.h>格式的语句,并捕获尖括号内的头文件名:

#include\s*<([^>]+)>

匹配逻辑

  • #include:匹配固定的预处理指令开头
  • \s*:匹配0个或多个空白字符(适配#include和<之间可能存在的空格、制表符)
  • <:匹配左尖括号
  • ([^>]+):捕获组,匹配所有非>的字符(即尖括号内的完整头文件名,支持带路径的格式如<sys/socket.h>)
  • >:匹配右尖括号

C++实现代码

利用C++11及以上标准库的<regex>组件实现提取功能,以下是完整可运行示例:

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

int main() {
    // 示例输入文本,可替换为实际代码内容
    const std::string code = R"(
        #include<stdio.h>
        #include <string.h>
        #include   <math.h>
        #include <sys/time.h>
        #include "local.h" // 双引号格式不会被匹配
    )";

    // 定义正则表达式
    const std::regex include_regex(R"(#include\s*<([^>]+)>)");
    std::smatch match;
    std::string::const_iterator search_start(code.cbegin());

    // 遍历所有匹配结果
    std::vector<std::string> headers;
    while (std::regex_search(search_start, code.cend(), match, include_regex)) {
        // 捕获组1即为尖括号内的头文件名
        headers.push_back(match[1].str());
        // 更新搜索起始位置,避免重复匹配
        search_start = match.suffix().first;
    }

    // 输出提取结果
    std::cout << "提取到的头文件名:\n";
    for (const auto& header : headers) {
        std::cout << "- " << header << "\n";
    }

    return 0;
}

代码说明

  • 用原始字符串字面量R"(...)"定义正则,避免转义字符的繁琐处理
  • std::smatch存储匹配结果,match[1]对应正则中的第一个捕获组(即目标头文件名)
  • 通过std::regex_search循环遍历所有匹配项,直到文本末尾
  • 若需要同时匹配#include "xxx.h"格式的双引号头文件,可调整正则为#include\s*(["<])([^">]+)\1,通过捕获组2提取文件名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:55:15