我想得到第一个#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/