expression substitution
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
David Young
2011-8-19
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 个评论
Andrei Bobrov
2011-8-19
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!