Regex to pull out C function prototype declarations?

前端 未结 8 615
星月不相逢
星月不相逢 2020-11-30 04:48

I\'m somewhere on the learning curve when it comes to regular expressions, and I need to use them to automatically modify function prototypes in a bunch of C headers. Does

相关标签:
8条回答
  • 2020-11-30 05:34

    As continue of the great Dean TH answer

    This will find

    • Only functions and not the declaration too
    • And Function that returns pointers

    ^([\w\*]+( )*?){2,}\(([^!@#$+%^;]+?)\)(?!\s*;)

    0 讨论(0)
  • 2020-11-30 05:36

    Assuming your code is formatted something like

    type name function_name(variables **here, variables &here)
    {
        code
    }
    

    Here’s a one-liner for Powershell:

    ls *.c, *.h | sls "^(\w+( )?){2,}\([^!@#$+%^]+?\)"
    

    Which returns results like:

    ...
    common.h:37:float max(float a, float b)
    common.h:42:float fclamp(float val, float fmin, float fmax)
    common.h:51:float lerp(float a, float b, float b_interp)
    common.h:60:float scale(float val, float valmin, float valmax, float min,
    float max)
    complex.h:3:typedef struct complex {
    complex.h:8:double complexabs(complex in)
    complex.h:13:void complexmult(complex *out, complex a, complex b)
    complex.h:20:void complexadd(complex *out, complex a, complex b)
    complex.h:27:int mandlebrot(complex c, int i)
    ...
    

    To see just the line without the file specifics, add format-table -property line (or abbreviated as ft -p line):

    ls *.c, *.h | sls "^(\w+( )?){2,}\([^!@#$+%^]+?\)" | format-table -p line
    

    Which returns:

    Line
    ----
    void render(SDL_Surface *screen)
    void saveframe(SDL_Surface *screen)
    int handleevents(SDL_Surface *screen)
    int WinMain(/*int argc, char* args[]*/)
    void printscreen(SDL_Surface *screen, unsigned int exclude)
    void testsection(char name[])
    void sdltests(SDL_Surface *screen, SDL_Window *window, int width, int height)
    int WinMain(/*int argc, char *argv[]*/)
    int random(int min, int max) {
    int main(int argc, char *argv[])
    

    BONUS: Explanation of the regex:

    ^(\w+(\s+)?){2,}\([^!@#$+%^]+?\)
    ^                                Start of a line
     (         ){2,}                 Create atom to appear to or more times
                                     (as many as possible)
      \w+(\s+)?                      A group of word characters followed by
                                     an optional space
                    \(            \) Literal parenthesis containing
                      [^!@#$+%^]+?   A group of 0 or more characters
                                     that AREN'T in “!@#$+%^”
    
    0 讨论(0)
提交回复
热议问题