You need to enable JavaScript to run this app. 如何在Python中使用正则表达式提取C代码头文件并拆分存储两类代码
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用正则表达式提取C代码头文件并拆分存储两类代码

C代码头文件与剩余代码拆分实现
import re

# 输入为完整C代码字符串,可直接替换为实际传入的内容
c_code = """#include <iostream>
#include <string>
#include conio.h

void main (void)
{
int b = 32;
int a=34;
int wao= 35;
}
"""

# 使用指定正则规则编译匹配模式
header_pattern = re.compile(r"#([^}]+)>|#([^}]+)\.h")

# 提取头文件内容与正则分组结果
any_header = []
match_groups = []

for match in header_pattern.finditer(c_code):
    # 收集完整匹配的头文件内容
    any_header.append(match.group(0).strip())
    # 提取正则两个分组的内容
    match_groups.append({
        "group1": match.group(1),
        "group2": match.group(2)
    })

# 头文件内容存入指定变量any
any = "\n".join(any_header)

# 剥离头文件后得到剩余代码,清理多余空行
remaining_code = header_pattern.sub("", c_code)
remaining_code = re.sub(r"\n{2,}", "\n", remaining_code).strip("\n")

输出结果说明

  • any 变量为所有匹配到的头文件内容:
#include <iostream>
#include <string>
#include conio.h
  • remaining_code 变量为剥离头文件后的剩余C代码:
void main (void)
{
int b = 32;
int a=34;
int wao= 35;
}
  • match_groups 存储每个匹配对应的两个分组提取结果,可直接调用查看,例如匹配#include conio.h对应的分组结果为{"group1": None, "group2": "include conio"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 18:06:03