如何使用正则表达式获取函数声明或定义

7 投票
7 回答
9885 浏览
提问于 2025-04-15 12:00

我想从C语言的文件中提取出函数的原型,比如下面这样的:

int my_func(char, int, float)
void my_func1(void)
my_func2()

我打算用正则表达式和Python来实现这个功能。

这是我用的正则表达式格式:".*\(.*|[\r\n]\)\n"

7 个回答

2

我觉得正则表达式在你的情况下不是最好的解决方案。因为它有很多陷阱,比如注释、字符串中的文本等等。不过,如果你的函数原型有共同的风格:

type fun_name(args);

那么 \w+ \w+\(.*\); 在大多数情况下应该是有效的:

mn> egrep "\w+ \w+\(.*\);" *.h
md5.h:extern bool md5_hash(const void *buff, size_t len, char *hexsum);
md5file.h:int check_md5files(const char *filewithsums, const char *filemd5sum);
2

看看你的C语言编译器有没有一个选项,可以输出一个只包含正在编译的函数原型的文件。对于gcc编译器来说,这个选项是 -aux-info FILENAME。

8

这是我为这类任务写的一个方便的小脚本,但它不会提供函数的类型信息。它只会列出函数的名称和参数列表。

# Exctract routine signatures from a C++ module
import re

def loadtxt(filename):
    "Load text file into a string. I let FILE exceptions to pass."
    f = open(filename)
    txt = ''.join(f.readlines())
    f.close()
    return txt

# regex group1, name group2, arguments group3
rproc = r"((?<=[\s:~])(\w+)\s*\(([\w\s,<>\[\].=&':/*]*?)\)\s*(const)?\s*(?={))"
code = loadtxt('your file name here')
cppwords = ['if', 'while', 'do', 'for', 'switch']
procs = [(i.group(2), i.group(3)) for i in re.finditer(rproc, code) \
 if i.group(2) not in cppwords]

for i in procs: print i[0] + '(' + i[1] + ')'

撰写回答