使用带有文本扫描的字符串读取子字符串和数字时的空白单元格

Blank cells while reading substring and numbers from with a string with textscan

我有一个文本文件,其中包含一行又一行的数据,格式类似于 xml,如下所示:

<item type="newpoint1" orient_zx="0.8658983248810842" orient_zy="0.4371062806139187" orient_zz="0.2432245678709263" electrostatic_force_x="0" electrostatic_force_y="0" electrostatic_force_z="0" cust_attr_HMTorque_0="0" cust_attr_HMTorque_1="0" cust_attr_HMTorque_2="0" vel_x="0" vel_y="0" vel_z="0" orient_xx="-0.2638371745169712" orient_xy="-0.01401379799313232" orient_xz="0.9644654264455047" pos_x="0" cust_attr_BondForce_0="0" pos_y="0" cust_attr_BondForce_1="0" pos_z="0.16" angvel_x="0" cust_attr_BondForce_2="0" angvel_y="0" id="1" angvel_z="0" charge="0" scaling_factor="1" cust_attr_BondTorque_0="0" cust_attr_BondTorque_1="0" cust_attr_BondTorque_2="0" cust_attr_Damage_0="0" orient_yx="0.4249823952954215" cust_attr_HMForce_0="0" cust_attr_Damage_1="0" orient_yy="-0.8993006799250595" cust_attr_HMForce_1="0" orient_yz="0.1031903618333235" cust_attr_HMForce_2="0" />

我只对“ ”中的值感兴趣,所以我尝试使用 textscan 阅读它。为此,我使用第一行并执行正则表达式 find/replace 将所有数字替换为 %f,将所有字符串替换为 %s,如下所示:

expression = '"[-+]?\d*\.?\d*"';
expression2 = '"\w*?"';

newStr = regexprep(firstline,expression,'"%f"');
FormatString = sprintf('%s',regexprep(newStr,expression2,'"%s"'));

我重新打开文件以使用以下调用读取带有字符串的文件:

while ~feof(InputFile) % Read all lines in file    
    data = textscan(InputFile,FormatString,'delimiter','\n');    
end

但我得到的只是一组空单元格。我看不出我的错误是什么 - 有人可以指出我正确的方向吗?

澄清:

Mathworks 为 textscan 提供了以下示例以删除文字文本,这正是我正在尝试做的。

"从上一示例数据的第二列的每个字段中删除文字文本 'Level'。"

filename = fullfile(matlabroot,'examples','matlab','scan1.dat');
fileID = fopen(filename);
C = textscan(fileID,'%s Level%d %f32 %d8 %u %f %f %s %f');
fclose(fileID);
C{2}

好的,今天用新的眼光看了这个之后,我发现了我的问题。

newStr = regexprep(firstline,expression,'"%f"');
FormatString = sprintf('%s',regexprep(newStr,expression2,'%q'));

data = textscan(InputFile,FormatString,'delimiter',' ');

字符串的替换需要切换到 %q 选项,该选项允许读取双引号内的字符串,并且需要将 textscan 的分隔符恢复为单身space。代码现在工作正常。