1

我正在将一个名为“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);

这段代码逐行返回每个变量的值,并输出:

answer1
answer2
answer3

我想要做的是修改我的正则表达式,以便我可以指定要检索的变量的名称,并让 Matlab 输出分配给指定变量的值。

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

answer2

问候

4

1 回答 1

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'
于 2012-04-16T18:26:52.153 回答