How do I replace multiple strings in text file at the same time?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
chlor thanks
el 17 de Sept. de 2019
Comentada: chlor thanks
el 18 de Sept. de 2019
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.
0 comentarios
Respuesta aceptada
Walter Roberson
el 17 de Sept. de 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 comentarios
Walter Roberson
el 18 de Sept. de 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'});
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!