2013-06-27 32 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但不能解決它;任何人的想法?