gpt4 book ai didi

python - 如何使用 Python 正则表达式获取 C++ 文件中的第一个 #include 语句?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:58 36 4
gpt4 key购买 nike

我想得到第一个#include尽可能快地使用 Python 正则表达式从 .cpp 文件中声明。

例如,

/* Copyright: 
This file is
protected
#include <bad.h>
*/

// Include files:
#undef A_MACRO
#include <stddef.h> // defines NULL
#include "logger.h"

// Global static pointer used to ensure a single instance of the class.
Logger* Logger::m_pInstance = NULL;

应该返回 #include <stddef.h>

我知道一种方法是删除所有评论,然后从剩余文本中获取第一行。但这似乎不够快,因为它必须遍历整个文件。如果我只需要第一个 #include声明,有什么有效的方法可以使用 Python 正则表达式来完成吗?

[更新 1] 一些人提到使用正则表达式不是一个好的解决方案。我知道这不是正则表达式的典型用例。但是有没有比正则表达式更好的方法来摆脱领先的评论?任何建议将不胜感激。

[更新 2] 感谢您的回答。但是好像还没有一个是我满意的。我的要求很简单:(1) 避免遍历整个文件来获取第一行。 (2) 需要正确处理前导评论。

最佳答案

您可以使用名为 CppHeaderParser 的库像这样:

import sys
import CppHeaderParser

cppHeader = CppHeaderParser.CppHeader("test.cpp")

print("List of includes:")
for incl in cppHeader.includes:
print " %s" % incl

为了让它工作你应该做

pip install cppheaderparser

输出:

List of includes:
<stddef.h> // defines NULL
"logger.h"

当然不是最好的结果,但这是一个开始。

关于python - 如何使用 Python 正则表达式获取 C++ 文件中的第一个 #include 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887092/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com