2013-06-27 29 views
1

的使用命令get_param(maskBlock,'MaskVariables'),我得到一个字符串,它看起来像这样:多次使用cellfun

'[email protected];[email protected];[email protected];[email protected];[email protected];' 

我想改变的数字和顺序加1,他们得到:

'[email protected];[email protected];[email protected];[email protected];[email protected];' 

这里我所编码:

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 "[email protected]" 

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

回答

6

这里是一个班轮:

str = '[email protected];[email protected];[email protected];[email protected];[email protected];'; 
regexprep(str,'(?<[email protected])(\d+)','${sprintf(''%d'',str2double($1)+1)}') 

比赛很容易:在字符串中的任何一点,回头看看@,如果fo然后匹配一个或多个连续的数字并捕获到令牌中。

更换str2double()捕获的标记,添加1和转换回一个整数。该命令以动态表达式'${command}'执行。

+0

非常好!在接受最终答案之前,我会尽力去理解一切(其他答案)。 –

1

如何:

+0

我也喜欢这个答案!将难以做出我的选择! –

+0

@m_power我会与奥列格的回答 – Shai

3

我有一个答案,而无需使用cellfun但使用令牌来代替:

%the given string 
str = '[email protected];[email protected];[email protected];[email protected];[email protected];'; 
%find the numbers using tokens 
regex = '[email protected](\d+);'; 
%dynamic replacement - take the token, convert it to a number - add 1 - and 
%convert it back to a string 
replace = '[email protected]${num2str(str2num($1)+1)};'; 
%here is your result - replace all found numbers with the replace string 
regexprep(str, regexp, replace) 
+0

另一个很好的答案! –

+0

我从来没有见过你!尽管strnnum和num2str损害了性能,但同样的精神。 – Oleg

+1

不错的答案。然而,使用'regexp'作为变量名是不明智的:它是一个内置的函数名! – Shai

0

Woops,昨天晚上我开始写这篇文章,然后我离开了工作,忘记完成了。只是一个使用textscan而不是正则表达式的例子。

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

我试着玩索引和cellfun来处理arrayfun但不能解决它;任何人的想法?