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

标签 python c++ regex

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

相关文章:

python - 高效分页查询结果

python - 在单独的线程中扭曲传输。

c++ - 如何为 memcpy 获取指向成员变量的指针

javascript - 我可以在 text.replace 函数的第二部分中使用正则表达式的部分吗?

Python:运行脚本的命令行应用程序。发送文件中的参数

C++:状态和控制模式

c++ - 为什么 C++ 编译器不消除 new 返回的指针的空检查?

java - 如何在java中使用正则表达式验证字符串

python - 验证日期(格式和值)

python - 我怎样才能用这样的高斯函数做更好的曲线拟合?