MATLAB读取每行文本并提取字符串后的数字
示例字符串
input_str = '2023-11-20 20:07:13,000 - training_logger - INFO - epoch: 1290.00000—>string1: 0.23039—>string2: 0.21709—>time_elapsed:17.15 sec';
clear all;
clc
filename = 'xx.log';
fid = fopen(filename, 'r');
% 提取“string1: ”和“string2: ”后面的数字
string1_pattern = '(?<=string1: )(\d+\.\d+)';
string2_pattern = '(?<=string2: )(\d+\.\d+)';
% 打开文件
file_id = fopen(filename, 'r');
% 读取文件内容
file_content = textscan(file_id, '%s', 'Delimiter', '\n');
file_content = file_content{1};
% 循环遍历每一行,提取匹配的浮点数并输出
for i = 1:length(file_content)
current_line = file_content{i};
string1_match = regexp(current_line, string1_pattern, 'match');
string2_match = regexp(current_line, string2_pattern, 'match');
% 转换匹配的数字
string1_list(i) = str2double(string1_match{1});
string2_list(i) = str2double(string2_match{1});
end
% 关闭文件
fclose(file_id);