我正在将一个文本文件读入Matlab,名为'test.txt',其结构如下:
$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);
这段代码逐行返回每个变量的值,并输出:
answer1
answer2
answer3
我想要做的是修改我的regexp表达式,以便我可以指定要检索的变量的名称,并让Matlab输出分配给指定变量的值。
E.g。如果我在我的代码中指定找到$ variable2的值,Matlab将返回:
answer2
此致
答案 0 :(得分:2)
一种可能的解决方案:
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'