Here's a regular expression that should match any MATLAB function declaration at the start of an m-file:
^\s*function\s+((\[[\w\s,.]*\]|[\w]*)\s*=)?[\s.]*\w+(\([^)]*\))?
And here's a more detailed explanation of the components:
^\s* # Match 0 or more whitespace characters
# at the start
function # Match the word function
\s+ # Match 1 or more whitespace characters
( # Start grouping 1
( # Start grouping 2
\[ # Match opening bracket
[\w\s,.]* # Match 0 or more letters, numbers,
# whitespace, underscores, commas,
# or periods...
\] # Match closing bracket
|[\w]* # ... or match 0 or more letters,
# numbers, or underscores
) # End grouping 2
\s* # Match 0 or more whitespace characters
= # Match an equal sign
)? # End grouping 1; Match it 0 or 1 times
[\s.]* # Match 0 or more whitespace characters
# or periods
\w+ # Match 1 or more letters, numbers, or
# underscores
( # Start grouping 3
\( # Match opening parenthesis
[^)]* # Match 0 or more characters that
# aren't a closing parenthesis
\) # Match closing parenthesis
)? # End grouping 3; Match it 0 or 1 times
Whether you use regular expressions or basic string operations, you should keep in mind the different forms that the function declaration can take in MATLAB. The general form is:
function [out1,out2,...] = func_name(in1,in2,...)
Specifically, you could see any of the following forms:
function func_name %# No inputs or outputs
function func_name(in1) %# 1 input
function func_name(in1,in2) %# 2 inputs
function out1 = func_name %# 1 output
function [out1] = func_name %# Also 1 output
function [out1,out2] = func_name %# 2 outputs
...
You can also have line continuations (...) at many points, like after the equal sign or within the argument list:
function out1 = ...
func_name(in1,...
in2,...
in3)
You may also want to take into account factors like variable input argument lists and ignored input arguments:
function func_name(varargin) %# Any number of inputs possible
function func_name(in1,~,in3) %# Second of three inputs is ignored
Of course, many m-files contain more than 1 function, so you will have to decide how to deal with subfunctions, nested functions, and potentially even anonymous functions (which have a different declaration syntax).