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

조회 수: 16 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by