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

16 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 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 Comments
Walter Roberson
Walter Roberson on 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'});

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!