Matlab:在txt中找到一个字符串并将其读入一个数字

时间:2015-04-13 02:55:12

标签: regex matlab

我有一个这样的输入文件:

number of elements = 4
number of nodes = 6
number of fixed points = 2
number of forces = 1
young = 2.0E8
poiss = 0.2
thickness = 0.002

node group
1 2 6
2 3 4
2 4 5
2 5 6

我用这个来读取文件

fid = fopen(input_file); 
tline = fgetl(fid);
line_number = 1;
while ischar(tline)
# this will locate the string, and find the number
    if ~isempty(strfind(tline,'number of elements'))
        NELEM = str2double(regexp(tline, '\d+', 'match')); 
    end
    if ~isempty(strfind(tline,'young'))
        YOUNG = str2double(regexp(tline, '\d+', 'match')); 
    end
    line_number=line_number+1;
    tline = fgetl(fid);     
end
fclose(fid);

第一个工作正常,但是,对于第二个YOUNG,输出实际上是[2 0 8](原始数字是2e8)正则表达式将字符串转换为array }。 对于poiss,它显示为[0,2]

如何将字符串转换为原始数字?

1 个答案:

答案 0 :(得分:1)

您的正则表达式需要将浮点数与指数匹配,请尝试将'\d+'更改为

'[0-9]*\.?[0-9]+([eE][0-9]+)?'

然后匹配带有可选小数点和指数的数字。例如:

str2double(regexp('young = 2.0E8', '[0-9]*\.?[0-9]+([eE][0-9]+)?', 'match'))

给出200000000