working with files, changing in the text

Hi
I really was trying to find out how to solve my task, but I can't. I need to read from the text 3 lines and change '7','8','9' to '!'
f=fopen('kik.txt','rt');
while feof(f)==0
s=fgetl(f);
for i=1:length(s)
if s(i)=='8'
s(i)='!';
end
if s(i)=='9'
s(i)='!';
end
if s(i)=='7'
s(i)='!';
end
end
end
disp(s)
fclose(f);

Answers (1)

Bhaskar R
Bhaskar R on 3 Feb 2020
Edited: Bhaskar R on 3 Feb 2020
data = fileread('kik.txt'); % your text file data
rep_data = regexprep(data, '[789]', '!'); % replaced data
fid = fopen('output_file.txt', 'wt'); % open file for writing
fprintf(fid,'%s', rep_data); % writing replaced data to text file
fclose(fid); % Close file

3 Comments

This regular expression confuses two competely different syntaxes:
regexprep(data, '[7|8|9]', '!')
The two syntaxes are:
  • (A|B|C) vertical bar used to separate options within grouping parentheses.
  • [XYZ] square brackets used to define a set of literal characters to match.
Within square brackets the vertical bar (pipe) is treated literally, so that Bhaskar R's regular expression will actually match the pipe character (which is most likely unintended). This is easy to demonstrate:
>> regexprep('|', '[7|8|9]', '!') % buggy regular expression matches pipe character.
ans =
!
The corrected regular expression would use either of the syntaxes I showed above, i.e.:
  • (7|8|9)
  • [789]
and then the regular expression will work as its author intended. For more information see:
My apologies, now corrected

Sign in to comment.

Products

Asked:

on 3 Feb 2020

Commented:

on 3 Feb 2020

Community Treasure Hunt

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

Start Hunting!