MATLAB: Is there a way to replace a paragraph of lines with another set of lines using regexprep

new lineregexprep

I want to replace the following text for example: (The difficulty is to regenerate the newline character in the output file.)
I love Maths
$a
I love Science
with…
I love History
$a
I love Ar
ts

Best Answer

"The problem is I guess the regexprep is not able to read and replace \n ,the newline character."
There is absolutely no reason why regular expressions cannot match a newline (linefeed) character. Most likely you are reading a file written on a PC (or for a PC), in which case that file actually contains a carriage return character followed by a linefeed character, so you simply forgot to match both of these characters in your regular expression.
Note that your use of fprintf is flawed/fragile, as you would find out as soon as you have any backspace or percent characters in that text. And you probably need to escape that dollar sign.
There is another potential flaw because when you open the file in text mode on a PC (you do not say what OS you are using) then any newlines (linefeeds) in the string will be converted to a carriage return followed by a linefeed (giving two carriage returns followed by a linefeed) when you write to the file... and then you would complain that when you open the file it shows blank lines between the lines of text. I got around this by not opening the file in text mode, so that it simply prints the exact characters that are already in the string.
So your fixed code would be something like this (untested as you did not upload a sample file):
rxp = 'I love Maths([\n\r]+\$a[\n\r]+)I love Science';
rpl = 'I love History$1I love Arts'
str = fileread('Replacement.txt');
str = regexprep(str,rxp,rpl);
[fid,msg] = fopen('Replacement.txt','w');
assert(fid>=3,msg)
fprintf(fid,'%s',str);
fclose(fid);
Personally I would avoid the whole issue of matching linefeed and carriage return characters by avoiding fileread altogether: open the file with fopen in text mode, read the file as one string using textscan, and then you really will have only newlines (linefeeds) to worry about in your regular expression. Much simpler, really, and works on all OSs.
PS: you might like to download my interactive regular expression helper tool, which lets you quickly test regular expressions and see regexp's outputs as you type: