How do I replace multiple strings in text file at the same time?

11 ビュー (過去 30 日間)
chlor thanks
chlor thanks 2019 年 9 月 17 日
コメント済み: chlor thanks 2019 年 9 月 18 日
I have a text file that looks something like this:
EGG SALAD ####
TREES
Line: A-A
Bacon
Line: B-B
More Broccolis
Line: C-C
and I would like to change the string A-A in my text file to C-C, and change the C-C to D-D.
In other words, what is the best way to change the string such that my results will look like this?
EGG SALAD ####
TREES
Line: C-C
Bacon
Line: B-B
More Broccolis
Line: D-D
I dont want this:
EGG SALAD ####
TREES
Line: D-D
Bacon
Line: B-B
More Broccolis
Line: D-D
I would also like the program to be able to read and save&replace the existing text file with same name/new name.

採用された回答

Walter Roberson
Walter Roberson 2019 年 9 月 17 日
S = fileread('YourFileNameHere.txt');
newS = regexprep(S, {'C-C', 'A-A'}, {'D-D', 'C-C'});
This replaces C-C with D-D everywhere first, and only then does it look to replace A-A with C-C .
This only works if all of the replacement texts like D-D are things that are not going to be replaced later.
If you needed to exchange A-A and C-C then you would need a strategy such as
newS = regexprep(S, {'C-C', 'A-A', '!TEMP!'}, {'!TEMP!', 'C-C', 'A-A'});
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 9 月 18 日
Replacing them "at the same time" would probably require constructing a Finite State Machine, perhaps a Turing Machine. In theory Finite State Machines and Turing Machines are quite efficient, but in practice at the MATLAB level they are less efficient because of all the looping and indexing required.
You can avoid the sanity checks using regexprep() by using a strategy such as
TS = regexprep(S, {'A-A', 'B-B', 'C-C', 'D-D'}, {'!T1!', '!T2!', '!T3!', '!T4!'});
newS = regexrep(TS, {'!T1!', '!T2!', '!T3!', '!T4!'}, {'B-B', 'D-D', 'A-A', 'C-C'});
chlor thanks
chlor thanks 2019 年 9 月 18 日
Genius!! I learnt a lot from your comments, thanks Walter!

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

その他の回答 (0 件)

カテゴリ

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