String body = "How are you? Fine.. Who are you";
If you want to replace all 'are you?' in the body with 'is it?', then we can use replaceAll method in String class.
But the code won't work if you write like this
body = body.replaceAll("are you?", "is it?");
Because the replaceAll method treats the first parameter as a regular expression pattern. So the ? mark in the "are you?" is treated as a meta character and it finds no matches for the regular expression and replaces nothing.
To treat meta characters as ordinary character, enclose the "are you?" string within \Q and \E i.e "\Qare you?\E".
body = body.replaceAll("\\Qare you?\\E", "is it?");
The above code will replace all the matches of "are you?" successfully.
If you want to replace all 'are you?' in the body with 'is it?', then we can use replaceAll method in String class.
But the code won't work if you write like this
body = body.replaceAll("are you?", "is it?");
Because the replaceAll method treats the first parameter as a regular expression pattern. So the ? mark in the "are you?" is treated as a meta character and it finds no matches for the regular expression and replaces nothing.
To treat meta characters as ordinary character, enclose the "are you?" string within \Q and \E i.e "\Qare you?\E".
body = body.replaceAll("\\Qare you?\\E", "is it?");
The above code will replace all the matches of "are you?" successfully.