expression substitution

Hi, I would like to use regexprep to substitute a simple expression for another in a text.
As an example, I have the following expression A=g*ABC+(1-g)*(CAD+d*EEA)+ZI/A , and would like to replace all occurrences of the word A with A_subs. The result would be A_subs=g*ABC+(1-g)*(CAD+d*EEA)+ZI/A_subs . Could you suggest a simple call to regexprep that would do this? Thanks, Junior

2 件のコメント

Friedrich
Friedrich 2011 年 8 月 19 日
So the ABC part has to stay and should not become A_subsBC?
Junior
Junior 2011 年 8 月 19 日
Hi Friedrich, the answer to your question is yes.

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

回答 (2 件)

David Young
David Young 2011 年 8 月 19 日

1 投票

s = 'A=g*ABC+(1-g)*(CAD+d*EEA)+ZI/A';
regexprep(s, '(^|\W)A($|\W)', '$1A_subs$2')
EDIT: See Walter Roberson's comment for a more elegant solution.

4 件のコメント

Walter Roberson
Walter Roberson 2011 年 8 月 19 日
s = 'A=g*ABC+(1-g)*(CAD+d*EEA)+ZI/A';
regexprep(s, '(\<A\>)', '$1_subs')
Oleg Komarov
Oleg Komarov 2011 年 8 月 19 日
@Walter: very elegant.
Andrei Bobrov
Andrei Bobrov 2011 年 8 月 20 日
Hi David, +1.
Hi Walter, super nice!
David Young
David Young 2011 年 8 月 20 日
Hi Andrei: thanks.
Hi Walter: wish I'd spotted that!

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

Andrei Bobrov
Andrei Bobrov 2011 年 8 月 19 日

0 投票

char(subs('A = ABC*g + ZI/A - (CAD + EEA*d)*(g - 1)','A','A_subs'))
ADD MORE variant
str='A=g*ABC+(1-g)*(CAD+d*EEA)+ZI/A'
t = regexp(str,'A=|[*/-+=]+A+$|[*/-+=]+A+[*/-+=]')
str2 = mat2cell(str,1,[1 diff(t) 1])
str2(strcmp(str2,'A'))={'A_subs'}
strout = cell2mat(str2)

2 件のコメント

Friedrich
Friedrich 2011 年 8 月 19 日
Little note: this works but requires Symbolic Math Toolbox.
Junior
Junior 2011 年 8 月 19 日
Hi Andrei, thanks for the answer. It is precisely a problem with the symbolic math toolbox that brought me here. Try replacing "A" with "I" and you will see it does not work. I need to do some substitutions before passing the expression to the symbolic math toolbox.

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

カテゴリ

ヘルプ センター および File ExchangeDeep Learning Toolbox についてさらに検索

質問済み:

2011 年 8 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by