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

标签 python regex

我只想得到像这样的函数原型(prototype)

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

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

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

最佳答案

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

# 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] + ')'

关于python - 如何使用正则表达式获取函数声明或定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/943391/

相关文章:

python - 返回匿名类或对象用作 'struct' 更好吗?

Node.JS 字符串仅匹配第一个字符

python - 如何通过手动填充 __class__ 单元格来使 super() 工作?

python - 有和没有 "as"子句的上下文管理器的区别

python - Pandas 索引数据框显示 : use top left empty box

javascript - 使用正则表达式检查 URL 哈希以查找部分和页面

javascript - ((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,} 适用于 regexpal.com,但不适用于 jsfiddle.net

python - 转换多个分类列

java - 使用正则表达式将 URI 中的 IP 地址替换为另一个 IP 地址

java - 使用正则表达式捕获预期结果