Python正则表达式从C头文件中提取数据

标签 python c regex

我有一个 C 头文件,其中包含大量枚举、类型定义和函数原型(prototype)。我想使用 Python 正则表达式 (re) 提取这些数据。我确实需要语法方面的帮助,因为每次学习时我似乎总是忘记它。

ENUMS
-----
enum
{
(tab character)(stuff to be extracted - multiple lines)
};

TYPES
-----
typedef struct (extract1) (extract2)


FUNCTIONS
---------
(return type)
(name)
(
(tab character)(arguments - multiple lines)
);

如果有人能指出我正确的方向,我将不胜感激。

最佳答案

我想你想要的就是这样的东西?

>>> re.findall('enum\s*{\s*([^}]*)};', 'enum {A,B,C};')
['A,B,C']
>>> re.findall("typedef\s+struct\s+(\w+)\s+(\w+);", "typedef struct blah blah;")
[('blah', 'blah')]

当然,语法有很多变化,而且函数要复杂得多,所以我将这些留给您,因为坦率地说,这些正则表达式已经足够脆弱和不优雅了。我强烈建议您使用实际的解析器,除非这只是一个一次性项目,其中稳健性完全不重要,并且您可以确定输入的格式。

关于Python正则表达式从C头文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10875977/

相关文章:

python-3.x - 如何在python中使用opencv-python将RGB888转换为RGB565?

c++ - IOServiceAddMatchingNotification 问题

c - 如何打印程序执行的次数?

PHP 在 string2 中查找 string1,其中 string1 源自 MySQL 表

c++ - 解析字符串的正则表达式模式

python - 从另一个脚本导入 python 脚本并使用参数运行它

python - python 中的线程 exit_request

javascript - 我需要在 javascript 中验证文件名和扩展名

python - 从 Amazon S3 迁移到 Azure 存储(Django Web 应用程序)

c - 在 AVR 微 Controller 上使用结构