user4377237
user4377237

Reputation: 11

Regex to detect begining of the c function body

I working on a perl script that prints the required function body from the c source file. i have written a regex to get to the start of the function body as

(/(void|int)\s*($function_name)\s*\(.*?\)\s*{/s

but this works only for functions returning void or int(basic types) how can i change this regex to handle user defined datatypes (struct or pointers)

Upvotes: 0

Views: 1817

Answers (1)

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

Try this one (untested!), although it does expect the function to start at the beginning of a line :

/
^                            # Start of line
\s*(?:struct\s+)[a-z0-9_]+   # return type
\s*\**                       # return type can be a pointer
\s*([a-z0-9_]+)              # Function name
\s*\(                        # Opening parenthesis
(
    (?:struct\s+)            # Maybe we accept a struct?
    \s*[a-z0-9_]+\**         # Argument type
    \s*(?:[a-z0-9_]+)        # Argument name
    \s*,?                    # Comma to separate the arguments
)*
\s*\)                        # Closing parenthesis
\s*{?                        # Maybe a {
\s*$                         # End of the line
/mi                          # Close our regex and mark as case insensitive

You can squeeze all of these into a single line by removing the whitespace and comments.

Parsing code with a regex is generally hard though, and this regex is not perfect at all.

Upvotes: 1

Related Questions