フィルターのクリア

replacing a string with another and vice versa

2 ビュー (過去 30 日間)
Patrick Mboma
Patrick Mboma 2012 年 10 月 3 日
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.
  3 件のコメント
Patrick Mboma
Patrick Mboma 2012 年 10 月 3 日
編集済み: Patrick Mboma 2012 年 10 月 3 日
I tried '(a|bb)\(d*\)' but it did not work.
Daniel Shub
Daniel Shub 2012 年 10 月 3 日
You forgot to escape the "d"

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

採用された回答

Matt Fig
Matt Fig 2012 年 10 月 3 日
編集済み: Matt Fig 2012 年 10 月 3 日
str = 'log(a(2))+a(3)*cosh(exp(bb(5)))'; % Initial string
str = regexprep(str,'(bb)\((\d)\)|(a)\((\d)\)','$1_$2')
  4 件のコメント
Patrick Mboma
Patrick Mboma 2012 年 10 月 3 日
Millions thanks Matt!
I also figured out it is possible to simplify things even further by writing
str2 = regexprep(str,'(bb|a)\((\d)\)','$1_$2')
then one can also do the inverse operation
str3 = regexprep(str2,'(bb|a)(\_)(\d)','$1($2)')
Matt Fig
Matt Fig 2012 年 10 月 3 日
Indeed!

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

その他の回答 (1 件)

per isakson
per isakson 2012 年 10 月 3 日
編集済み: per isakson 2012 年 10 月 4 日
A start of one way to use regular expression:
string = regexprep( string, '(?<=a)\((\d+)\)', '_$1' );
string = regexprep( string, '(?<=bb)\((\d+)\)', '_$1' );
.
-- in one line ---
Look for "(one or more digits)" that comes directly after "bb" or "a"
>> string = regexprep( string, '(?<=((bb)|a))\((\d+)\)', '_$1' )
string =
log(a_2)+a_3*cosh(exp(bb_5)
  • (?<=((bb)|a)) "Look behind from current position and test if expr is found." Where expr evaluate to "a" or "bb".
--- another one-liner ---
>> str = log(a(2))+a(3)*cosh(exp(bb(5));
>> regexprep( str, '((bb)|a)\((\d+)\)', '$1_$2' )
ans =
log(a_2)+a_3*cosh(exp(bb_5)
  • (bb)|a stands for "bb" or "a"
  • (expr) stands for group regular expressions and capture tokens
  • *\(* stands for "("
  • \d+ stands for one ore more digits
  3 件のコメント
per isakson
per isakson 2012 年 10 月 3 日
編集済み: per isakson 2012 年 10 月 3 日
Yes it is, but why bother? Matt, has done it. With regular expressions one must not make it more complicated than one master.
per isakson
per isakson 2012 年 10 月 4 日
See above

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

カテゴリ

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