在处理正则表达式时,您别无选择。如果要将数字用于正则表达式,则必须将数字转换为字符串。但是,Luis Mendo 的方法更简单,因为您只需要在逻辑分支中添加另一个 if 语句。那个方法也不错,而且更简单。
如果您不想这样做并且想在正则表达式中使用数字,我们可以跟踪您的元胞数组中的哪些元素以数字开头,将这些数字转换为字符串,使用regexprep,然后完成后将这些条目转换回数字。
您可以使用cellfun 检查元胞数组中的哪些元素是数字。然后,将这些元素转换为字符串,进行处理,然后再转换回来。首先通过isnumeric检查每个元素是否为数字。在此之后,您可以使用num2str 将数字转换为字符串。之后,使用str2num 将字符串转换回数字。换句话说,这样做:
myCell1 = {'';'"some words"';64;23;'"words"'};
myCell2={'';'more words';'more stuff';46;15};
Cell={myCell1, myCell2};
newCellArray = cell(1,numel(Cell)); %// Place output cell array here
for i = 1 : numel(Cell)
%// Extract i'th cell
cel = Cell{i};
%// Which ones are numbers?
whichAreNumbers = cellfun(@isnumeric, cel);
%// Convert those numbers into strings
outStrings = cellfun(@num2str, cel(whichAreNumbers), 'uni', false);
%// Assign back into cell
cel(whichAreNumbers) = outStrings;
%// Apply regexprep now
newCell = regexprep(cel, '^"|"$', '');
%// Convert the numbers back
outVals = cellfun(@str2num, newCell(whichAreNumbers), 'uni', false);
newCell(whichAreNumbers) = outVals;
%// Place in master output cell array
newCellArray{i} = newCell;
end
此时的输出为:
>> celldisp(newCellArray)
newCellArray{1}{1} =
''
newCellArray{1}{2} =
some words
newCellArray{1}{3} =
64
newCellArray{1}{4} =
23
newCellArray{1}{5} =
words
newCellArray{2}{1} =
''
newCellArray{2}{2} =
more words
newCellArray{2}{3} =
more stuff
newCellArray{2}{4} =
46
newCellArray{2}{5} =
15
如您所见,数字仍然保留,但每个字符串的引号都被删除了。