在Matlab中使用regexp从文本文件返回变量的值 [英] Use regexp in Matlab to return the value of a variable from a text file
问题描述
我正在将一个名为'test.txt'的文本文件读取到Matlab中,其结构如下:
I am reading a text file into Matlab called 'test.txt' which is structured as follows:
$variable1 = answer1;
$variable2 = answer2;
$variable3 = answer3;
我使用以下代码段将文本文件逐行读入Matlab:
I read the text file into Matlab line by line using the following segment of code:
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);
这段代码逐行返回每个变量的值,并输出:
This piece of code returns the value of each variable line by line and would output:
answer1
answer2
answer3
我要做的是修改我的regexp表达式,以便我可以指定要检索的变量的名称,并使Matlab输出分配给指定变量的值.
What I want to do is modify my regexp expression so that I can specify the name of the variable to retrieve and have Matlab output the value assigned to the variable specified.
例如如果我在代码中指定以查找$ variable2的值,Matlab将返回:
E.g. If I specify in my code to find the value of $variable2, Matlab would return:
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'
这篇关于在Matlab中使用regexp从文本文件返回变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!