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

16 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 17 Sep. 2019
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 Kommentare
Walter Roberson
Walter Roberson am 18 Sep. 2019
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 am 18 Sep. 2019
Genius!! I learnt a lot from your comments, thanks Walter!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by