MATLAB: Replacing a string with another and vice versa

parserregular expressionstring

Hi, I would like to write two functions:
1- replace all occurrences of 'a(number)' and 'bb(number)' with respectively 'a_number' and 'bb_number'. More concretely, a(1) would become a_1 and bb(1285) would become bb_1285. the typical string would look like
string='log(a(2))+a(3)*cosh(exp(bb(5))'
and the result would be
string='log(a_2)+a_3*cos(exp(bb_5))'
2- do the inverse operation
Is there any efficient way of doing this? My sense is that it can be done with regular expressions but I am just a beginner on that front and I would not know how to go about this. Your help will be appreciated.
thanks,
Pat.

Best Answer

str = 'log(a(2))+a(3)*cosh(exp(bb(5)))'; % Initial string
str = regexprep(str,'(bb)\((\d)\)|(a)\((\d)\)','$1_$2')