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

use*_*391 4 python regex

我想只获得函数原型

int my_func(char, int, float)
void my_func1(void)
my_func2()
Run Code Online (Sandbox Code Playgroud)

从C文件使用正则表达式和python.

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

Nic*_*kis 6

这是我为这些任务编写的一个方便的脚本,但它不会给出函数类型.它仅适用于函数名称和参数列表.

# 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] + ')'
Run Code Online (Sandbox Code Playgroud)