Dynamic regular expression replacement: token number

8 ビュー (過去 30 日間)
Davy Decorps
Davy Decorps 2020 年 3 月 19 日
編集済み: Stephen23 2020 年 3 月 23 日
Hi,
I was trying to do something that sounded simple... but I'm stuck!
Trying to replace matched tokens using regexprep, but I'd like to replace them with there token number dynamically.
For example:
regexprep('(first matched_token)_fjezhfjksdhf_(second matched_token)','matched_token', 'matchednumber_$DUNNO?')
would output
(first matchednumber_1)_fjezhfjksdhf_(second matchednumber_2)
Any idea appreciated, thanks!

回答 (2 件)

Sai Veeramachaneni
Sai Veeramachaneni 2020 年 3 月 23 日
You can use something similar to below code to simulate the required behavior.
str='(first matched_token)_fjezhfjksdhf_(second matched_token)';
i=0;
while true
i=i+1;
temp=regexprep(str,'matched_token',strcat("matchednumber_",num2str(i)),'once');
if isequal(temp,str)
break
end
str=temp;
end
str

Stephen23
Stephen23 2020 年 3 月 23 日
編集済み: Stephen23 2020 年 3 月 23 日
It can be done with one dynamic replacement expression:
>> str = '(1st MT)_fjezhfjksdhf_(2nd MT)';
>> rgx = 'MT';
>> out = regexprep(str, rgx, 'MN_${num2str(1+numel(regexp($`,rgx)))}')
out =
(1st MN_1)_fjezhfjksdhf_(2nd MN_2)
See:

カテゴリ

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