How to replace a word with another word in a cell array (case insensitive)

Hi I am trying to replace words found in a string with a given value (case insensitive)
str = 'lemon lemontea Lemongrass lime';
replaceword = 'lemon' %case insensitive
withthis = {'berry', 'apple', 'flower'};
Assume that we will be given with enough number of words to replace all the occurance of the word
I want to return this:
newstr = 'berry appletea flowergrass lime';
I tried to use strrep but it would replace for Lemon...

 Accepted Answer

Method one: loop and regexprep:
for k = 1:numel(withthis)
str = regexprep(str,replaceword,withthis{k},'once','ignorecase');
end
Method two: regexpi and indexing:
>> spl = regexpi(str,replaceword,'split');
>> spl(2,1:end-1) = withthis;
>> str = sprintf('%s',spl{:})
str =
berry appletea flowergrass lime

6 Comments

+1, once was the tricky part for me , the rest was done!
I found this really helpful!
But I am trying to implement this with a textfile...When I use this concept, it repeats the for loop 3 times and return same line three times with three different replaced words. Could you help me more on this?
lets say the textfile ('lemon.txt') hold these three lines:
lemon blah blah blah
blah limelemon blah blah blah
blah blah blah blah lemontree
replaceword and withthis remain the same....
filename = 'lemon.txt';
replaceword = 'lemon';
withthis = {'berry','apple','flower'};
fh = fopen(filename, 'r');
line = fgetl(fh);
while ischar(line)
for k = 1:numel(ca)
newline = regexprep(line, word, ca{k}, 'once', 'ignorecase');
fprintf(newfh, '%s\n', newline);
end
line = fgetl(fh);
end
this is what I have so far.. but its returning a wrong data
str = fileread('temp0.txt');
... replace using either method
fid = fopen('temp1.txt','w'); % not text mode!
fprintf(fid,'%s',str);
fclose(fid);
Because one of the withthis words includes the very substring that you are replacing you will have to use the second method, for example:
>> replaceword = 'ye';
>> withthis = {'HELLO','BYE','MEOW'};
>> str = fileread('cartiSnapping.txt');
>> spl = regexp(str,replaceword,'split','ignorecase');
>> spl(2,1:end-1) = withthis;
>> str = sprintf('%s',spl{:})
str =
I got a lot on my mind HELLOah
I got a lot on my mind huh BYEah
I got a lot on my mind huh Whoa
She got a lot on her mind ooh
She got a lot on her mind ooh MEOWah
I got a lot on my mind ooh
I got a lot on my mind
and then save to file like I showed earlier.

Sign in to comment.

More Answers (0)

Asked:

on 16 Jul 2020

Commented:

on 16 Jul 2020

Community Treasure Hunt

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

Start Hunting!