1

使用命令get_param(maskBlock,'MaskVariables'),我得到一个如下所示的字符串:

'AB=@1;AC=@2;AD=@3;AE=@4;..AZ=@26;'

我想更改数字并将它们加 1 以获得:

'AB=@2;AC=@3;AD=@4;AE=@5;..AZ=@27;'

这是我编码的内容:

strSplit = regexp(theStringFromGetParam , ';', 'split')'; % split the string at the ; to get multiple strings
str1 = cellfun(@(x) str2double(regexp(x,'(\d+)','tokens','once'))+1, strSplit, 'UniformOutput', false); % cell containing the last numbers
str2 = cellfun(@(x) regexp(x,'(\w+)(\W+)','tokens','once'), strSplit, 'UniformOutput', false); % cell containing everything that is not a number
str3 = cellfun(@(x) strcat(x{1}, x{2}), str2, 'UniformOutput', false); % join the two parts from the line above
str4 = cellfun(@(x,y) strcat(x,num2str(y)), str3, str1, 'UniformOutput', false); % join the number numbers with the "letters=@"

它有效,但我几乎可以肯定有更好的方法来做到这一点。任何人都可以帮助我找到比使用 4 次命令更好的方法cellfun吗?

4

4 回答 4

6

这是一个单行:

str = 'AB=@1;AC=@2;AD=@3;AE=@4;AZ=@26;';
regexprep(str,'(?<=@)(\d+)','${sprintf(''%d'',str2double($1)+1)}')

匹配很简单:在字符串中的任何位置,向后查找一个,@如果找到,则继续匹配一个或多个连续数字并捕获到一个标记中。

替换str2double()捕获的令牌,添加并1转换回整数。该命令使用动态表达式执行'${command}'

于 2013-06-27T19:11:51.890 回答
3

我有一个不使用 cellfun 而是使用令牌的答案:

%the given string
str = 'AB=@1;AC=@2;AD=@3;AE=@4;..AZ=@26;';
%find the numbers using tokens
regex = '=@(\d+);';
%dynamic replacement - take the token, convert it to a number - add 1 - and
%convert it back to a string
replace = '=@${num2str(str2num($1)+1)};';
%here is your result - replace all found numbers with the replace string
regexprep(str, regexp, replace)
于 2013-06-27T19:00:20.037 回答
1

怎么样:

num = regexp( theStringFromGetParam, '@(\d+);', 'tokens' ); % get the numbers
num = cellfun( @(x) str2double(x), num ); % convert to numbers
frmt = regexprep( theStringFromGetParam, '@(\d+);', '@%%d;' );
sprintf( frmt, num ); % print the updated numbers into the format string.
于 2013-06-27T18:42:39.907 回答
0

糟糕,我昨晚下班前开始写这篇文章,忘了写完。只是一个使用 textscan 而不是 regexp 的示例。

ManyCells=textscan(theStringFromGetParam,'%s%d', 'delimiter','@;');
S=arrayfun(@(x) sprintf('%s@%d;',ManyCells{1}{x},1+ManyCells{2}(x)),1:length(ManyCells{1}),'uniformoutput',false)
NewString=cat(2,S{:});

我尝试使用索引和 cellfun 来处理 arrayfun,但无法解决;有什么想法吗?

于 2013-06-28T10:37:02.647 回答