how to get the function declaration or definitions using regex

后端 未结 7 996
野的像风
野的像风 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:04

    I think this one should do the work:

    r"^\s*[\w_][\w\d_]*\s*.*\s*[\w_][\w\d_]*\s*\(.*\)\s*$"
    

    which will be expanded into:

    string begin:   
            ^
    any number of whitespaces (including none):
            \s*
    return type:
      - start with letter or _:
            [\w_]
      - continue with any letter, digit or _:
            [\w\d_]*
    any number of whitespaces:
            \s*
    any number of any characters 
      (for allow pointers, arrays and so on,
      could be replaced with more detailed checking):
            .*
    any number of whitespaces:
            \s*
    function name:
      - start with letter or _:
            [\w_]
      - continue with any letter, digit or _:
            [\w\d_]*
    any number of whitespaces:
            \s*
    open arguments list:
            \(
    arguments (allow none):
            .*
    close arguments list:
            \)
    any number of whitespaces:
            \s*
    string end:
            $
    

    It's not totally correct for matching all possible combinations, but should work in more cases. If you want it to be more accurate, just let me know.

    EDIT: Disclaimer - I'm quite new to both Python and Regex, so please be indulgent ;)

提交回复
热议问题