如果您的问题仅涉及简单情况,即您想解析文件中主要函数的
function declaration line(即您不会处理
local functions,
nested functions或
anonymous functions),则可以使用一些标准字符串操作和
regular expressions提取输入和输出参数名称,
如它们在文件中出现的那样。函数声明行具有标准格式,但您必须考虑到由于以下几个原因而产生的一些变化:
(结果证明处理块注释是最棘手的部分...)
我编写了一个名为get_arg_names
的函数来处理上述所有内容。如果您给它一个函数文件的路径,它将返回包含输入和输出参数字符串的两个单元格数组(如果没有则为空单元格数组)。请注意,具有可变输入或输出列表的函数将简单地列出'varargin'
或'varargout'
,分别用于变量名称。这是该函数:
function [inputNames, outputNames] = get_arg_names(filePath)
fid = fopen(filePath);
defLine = '';
while all(isspace(defLine))
defLine = strip_comments(fgets(fid));
end
index = strfind(defLine, '...');
while ~isempty(index)
defLine = [defLine(1:index-1) strip_comments(fgets(fid))];
index = strfind(defLine, '...');
end
fclose(fid);
matchStr = '\s*function\s+';
if any(defLine == '=')
matchStr = strcat(matchStr, '\[?(?<outArgs>[\w, ]*)\]?\s*=\s*');
end
matchStr = strcat(matchStr, '\w+\s*\(?(?<inArgs>[\w, ]*)\)?');
argStruct = regexpi(defLine, matchStr, 'names');
if isfield(argStruct, 'inArgs') && ~isempty(argStruct.inArgs)
inputNames = strtrim(textscan(argStruct.inArgs, '%s', ...
'Delimiter', ','));
else
inputNames = {};
end
if isfield(argStruct, 'outArgs') && ~isempty(argStruct.outArgs)
outputNames = strtrim(textscan(argStruct.outArgs, '%s', ...
'Delimiter', ','));
else
outputNames = {};
end
function str = strip_comments(str)
if strcmp(strtrim(str), '%{')
strip_comment_block;
str = strip_comments(fgets(fid));
else
str = strtok([' ' str], '%');
end
end
function strip_comment_block
str = strtrim(fgets(fid));
while ~strcmp(str, '%}')
if strcmp(str, '%{')
strip_comment_block;
end
str = strtrim(fgets(fid));
end
end
end