How to use regexprep to modify strings while keeping constituent numbers intact?
10 ビュー (過去 30 日間)
古いコメントを表示
I have a cell array of strings:
str = {'$d(V_1)$', ...
'$d(V_2)$', ...
'$d(V_3)$'}
I wish to convert the cell array of strings into:
strDesired = {'$function(a_{d(V_1)})$', ...
'$function(a_{d(V_2)})$', ...
'$function(a_{d(V_3)})$'}
I tried using regexprep but I do not know how to extract and put in the same number in the new string strNew as the original str. Here I'm replacing the number with x just to demonstrate my incomplete solution:
patternToFind = 'd\(V_[1-9]\)';
patternToReplaceWith = 'function\(a_\{d\(V_x\)\}\)';
strNew = regexprep(str, patternToFind, patternToReplaceWith)
Could someone assist me in forming a patternToReplaceWith which will help me arrive at strDesired after performing the regexprep?
0 件のコメント
採用された回答
Voss
2022 年 6 月 10 日
編集済み: Voss
2022 年 6 月 10 日
You can capture the V_1, V_2, etc., in tokens, then place those tokens in the output of regexprep by specifying $1 in patternToReplaceWith
str = {'$d(V_1)$', ...
'$d(V_2)$', ...
'$d(V_3)$'};
patternToFind = 'd\((V_[1-9])\)';
% ^ ^ I added parentheses here to capture tokens of the form V_[1-9]
patternToReplaceWith = 'function\(a_\{d\($1\)\}\)';
% ^^ tell regexprep to use token #1 (the only token) #1
strNew = regexprep(str, patternToFind, patternToReplaceWith)
2 件のコメント
Voss
2022 年 6 月 10 日
You're welcome! I'm glad you got it figured out. Thanks for accepting my answer anyway!
その他の回答 (1 件)
参考
カテゴリ
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!