如何使用正则表达式获取函数声明或定义 [英] how to get the function declaration or definitions using regex

查看:58
本文介绍了如何使用正则表达式获取函数声明或定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想得到像

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

来自使用正则表达式和 python 的 C 文件.

from C files using regex and python.

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

Here is my regex format: ".*\(.*|[\r\n]\)\n"

推荐答案

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

This is a convenient script I wrote for such tasks but it wont give the function types. It's only for function names and the argument list.

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

这篇关于如何使用正则表达式获取函数声明或定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆