how to get the function declaration or definitions using regex

后端 未结 7 1029
野的像风
野的像风 2020-12-16 06:43

I want to get only function prototypes like

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

from C files using regex and pytho

7条回答
  •  别那么骄傲
    2020-12-16 07:07

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

提交回复
热议问题