How to substitute numbers in a string with repeated strings?

5 ビュー (過去 30 日間)
German Preciat Gonzalez
German Preciat Gonzalez 2017 年 5 月 8 日
編集済み: Stephen23 2017 年 5 月 9 日
I have many different strings with different numbers with this format:
str='A + 2 B -> D + 3 E';
I would like to replace the numbers with repeated strings so I can have
str='A + B + B -> D + E + E + E';
I did it with so many lines but it looks so ugly and I would like to ask you if you know a better way
Thanks
  1 件のコメント
Stephen23
Stephen23 2017 年 5 月 8 日
編集済み: Stephen23 2017 年 5 月 8 日
I am sure that this could be done in just one line of code using regexprep and a dynamic replacement string. When I get back to a computer with MATLAB I will give it a try.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2017 年 5 月 9 日
編集済み: Stephen23 2017 年 5 月 9 日
This is easy with a dynamic regular expression, you can adjust it to suit your needs:
>> str = 'A + 2 B -> D + 3 E';
>> regexprep(str,'(\s+)([+-])\s+(\d+)\s+([A-Z]+)','${repmat([$1,$2,$1,$4],1,str2double($3))}')
ans =
A + B + B -> D + E + E + E

その他の回答 (2 件)

KL
KL 2017 年 5 月 8 日
編集済み: KL 2017 年 5 月 8 日
something like this?
str={'A + 2 B -> D + 3 E'};
old = {'2', '3'};
new = {'B +','E +'};
for i=1:numel(old)
str = strrep(str,old(i),new(i))
if you really want to use character array, a little tweak will do,
str=['A + 2 B -> D + 3 E'];
old = {'2', '3'};
new = {'B +','E +'};
for i=1:numel(old)
str = strrep(str,old{i},new{i})
end
end
As Stephen mentioned, regexprep makes it even more easier without a loop,
str=['A + 2 B -> D + 3 E']
old = {'2', '3'}
new = {'B +','E +'}
newStr = regexprep(str,old,new)
  4 件のコメント
KL
KL 2017 年 5 月 8 日
ok, sure.
German Preciat Gonzalez
German Preciat Gonzalez 2017 年 5 月 8 日
Thanks for the feedback, but I would like to apply a script to any formula, not just for the example I showed
Additionally, I would like to repeat the value "3 E" three times as in the example.

サインインしてコメントする。


Rik
Rik 2017 年 5 月 8 日
My first thought is using repmat, but usually when my first thought is repmat, there is a better solution using sprintf. So someone might have a way faster and more elegant solution than this.
First use isstrprop to figure out the position of the digits ( ind=isstrprop(str,'digit'); ), then loop over the numbers ( for pos=length(find(ind)):-1:1 ) to replicate the correct part.
A more important question is your source. Can you prevent your source to output this format? That would make processing with Matlab less clunky and more clear cut.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by