让我说我有这个范围的数字,我想扩大这些间隔。我的代码出什么问题了?我得到的答案是不正确的:
间隔只能用-每一个‘事物’是分隔的;
我希望产出是:-6 -3 -2 -1 3 4 5 7 8 9 10 11 15 17 18 19 20
range_expansion('-6;-3--1;3-5;7-11;14;15;17-20 ')
function L=range_expansion(S)
% Range expansion
if nargin < 1;
S='[]';
end
if all(isnumeric(S) | (S=='-') | (S==',') | isspace(S))
error 'invalid input';
end
ixr = find(isnumeric(S(1:end-1)) & S(2:end) == '-')+1;
S(ixr)=':';
S=['[',S,']'];
L=eval(S) ;
end
ans =
-6 -2 -2 -4 14 15 -3发布于 2022-11-02 22:57:37
您可以使用regexprep来用,代替;,用:代替定义范围的-。这些-是由一个数字前面的数字识别出来的。结果是一个字符串,可以使用str2num将其转换为所需的输出。但是,由于此函数计算字符串,为了安全起见,首先检查该字符串是否只包含允许的字符:
in = '-6;-3--1;3-5;7-11;14;15;17-20 '; % example
assert(all(ismember(in, '0123456789 ,;-')), 'Characters not allowed') % safety check
out = str2num(regexprep(in, {'(?<=\d)-' ';'}, {':' ','})); % replace and evaluatehttps://stackoverflow.com/questions/74295679
复制相似问题