我想#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;
Run Code Online (Sandbox Code Playgroud)
应该返回 #include <stddef.h>
我知道一种方法是删除所有注释,然后从剩余文本中获取第一行。但这似乎不够快,因为它必须遍历整个文件。如果我只需要第一个#include语句,是否有任何有效的方法可以使用 Python 正则表达式来完成它?
[更新 1] 有几个人提到使用正则表达式不是一个好的解决方案。我知道这不是正则表达式的典型用例。但是有没有比正则表达式更好的方法来摆脱主要注释呢?任何建议将不胜感激。
[更新2] 感谢您的回答。但似乎还没有一个让我满意的。我的要求很简单:(1)避免遍历整个文件来获取第一行。(二)要正确处理领导意见。
You can use a library called CppHeaderParser like this:
import sys
import CppHeaderParser
cppHeader = CppHeaderParser.CppHeader("test.cpp")
print("List of includes:")
for incl in cppHeader.includes:
print " %s" % incl
Run Code Online (Sandbox Code Playgroud)
For it to work you should do
pip install cppheaderparser
Run Code Online (Sandbox Code Playgroud)
It outputs:
List of includes:
<stddef.h> // defines NULL
"logger.h"
Run Code Online (Sandbox Code Playgroud)
Certainly not the best result, but it's a start.