string text manipulation - adding data based on previous data in the string

2 ビュー (過去 30 日間)
michael
michael 2022 年 6 月 2 日
編集済み: Stephen23 2022 年 6 月 2 日
Hi,
I have a string (char array) looking as follows:
Time,<Message_CMD>element1,<other_meesage>elemenX,<Message_CMD>element2,<Message_RPT>element3,
I'd like to change the string so that the element will contain the type of the message
Time,<Message_CMD>element1CMD,<other_meesage>elemenX,<Message_CMD>element2CMD,<Message_RPT>element1RPT,
What is the simplest way to do it?
EDIT: note that element1 is both CMD and RPT

採用された回答

Stephen23
Stephen23 2022 年 6 月 2 日
T = 'Time,<Message_CMD>element1,<other_meesage>elemenX,<Message_CMD>element2,<Message_RPT>element3'
T = 'Time,<Message_CMD>element1,<other_meesage>elemenX,<Message_CMD>element2,<Message_RPT>element3'
U = regexprep(T,'([A-Z]+)>([^,]+)','$1>$2$1')
U = 'Time,<Message_CMD>element1CMD,<other_meesage>elemenX,<Message_CMD>element2CMD,<Message_RPT>element3RPT'
  3 件のコメント
Walter Roberson
Walter Roberson 2022 年 6 月 2 日
If I read correctly element3 needs to become element1RPT with the change in digit
Stephen23
Stephen23 2022 年 6 月 2 日
編集済み: Stephen23 2022 年 6 月 2 日
"Can you please elaborate the parameters?"
Here is a breakdown of the match (regular) and replacement expressions:
regexprep(T,'([A-Z]+)>([^,]+)','$1>$2$1')
% ( ) group 1
% [A-Z]+ match one or more capital letters
% > match literal ">" character
% ( ) group 2
% [^,]+ match one or more non-commas
% $1 group 1
% > literal ">"
% $2 group 2
% $1 group 1 (this adds the text you want)
So the regular expression matches one or more capital letters followed by ">" followed by one or more non-commas (any character that is not a comma). For example:
'Time,<Message_CMD>element1,<other_meesage>elemenX,<Message_CMD>element2,<Message_RPT>element3'
% ^^^ group 1
% ^ literal ">"
% ^^^^^^^^ group 2
It then replaces all of that matched text with exactly the same text, plus it appends group 1 on the end.
Now that I think about it, I could have saved one character by placing ">" inside group 2.

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2022 年 6 月 2 日
編集済み: Walter Roberson 2022 年 6 月 2 日
regexprep(S, {'element[12]', 'element3'}, {'$1CMD', '$1RPT'})
  2 件のコメント
michael
michael 2022 年 6 月 2 日
Please have a look on the update of the question
Walter Roberson
Walter Roberson 2022 年 6 月 2 日
regexprep(S, {'element[12]', 'element3'}, {'$1CMD', 'element1RPT'})

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


David Hill
David Hill 2022 年 6 月 2 日
m=replace(m,'element1','element1CMD');
m=replace(m,'element2','element2CMD');
m=replace(m,'element3','element3RPT');
  1 件のコメント
michael
michael 2022 年 6 月 2 日
Please have a look on the update of the question

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R14SP2

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by