在Matlab中使用regexp从文本文件返回变量值

在Matlab中使用regexp从文本文件返回变量值,regex,matlab,Regex,Matlab,我正在将一个名为“test.txt”的文本文件读入Matlab,其结构如下: $variable1 = answer1; $variable2 = answer2; $variable3 = answer3; 我使用以下代码段逐行将文本文件读入Matlab: fid = fopen('test.txt.'); tline = fgetl(fid); tracks = {}; while ischar(tline) tracks{end+1} = regexp(tline, '(?&l

我正在将一个名为“test.txt”的文本文件读入Matlab,其结构如下:

$variable1 = answer1; 
$variable2 = answer2;
$variable3 = answer3;
我使用以下代码段逐行将文本文件读入Matlab:

fid = fopen('test.txt.');
tline = fgetl(fid);
tracks = {};
while ischar(tline)
    tracks{end+1} = regexp(tline, '(?<=^.*\=\s*)(.*)(?=\s*;$)', 'match', 'once');
    tline = fgetl(fid);
end
fclose(fid);
我想做的是修改我的regexp表达式,这样我就可以指定要检索的变量的名称,并让Matlab输出指定给该变量的值

例如,如果我在代码中指定查找$variable2的值,Matlab将返回:

answer2
考虑一种可能的解决方案:

function [tracks] = GetAnswer(Filename, VariableName)
fid = fopen(Filename);
tline = fgetl(fid);
tracks = {};

% prefix all $ in VariableName with \ for `regexp` and `regexprep`
VariableName = regexprep(VariableName, '\$', '\\$');

while ischar(tline)
    if (regexp(tline, [ '(', VariableName, ')', '( = )', '(.*)', '(;)' ]))
        tracks{end+1} = regexprep(tline, [ '(', VariableName, ')', '( = )', '(.*)', '(;)' ], '$3');
        % if you want all matches (not only the 1st one),
        % remove the following `break` line.
        break;
    end
    tline = fgetl(fid);
end

fclose(fid);
return
你可以这样称呼它:

Answer = GetAnswer('test.txt', '$variable2')

Answer = 
'answer2'
Answer = GetAnswer('test.txt', '$variable2')

Answer = 
'answer2'