0

I want to escape back slashes in a Java string. I tried to use the below code-

public static String escapeString(String str)
{
   return str.replace("\\", "\\\\");
}

This works like a charm. But, then I noticed that I also have some scenarios where the "\" character is used intentionally for escaping some standard characters like '\n', '\r', '\t' etc. Well, I don't want these '\' characters to get escaped because then these will become like '\n', '\r', '\t' which is not intended. Bellow example will make it clearer-

I/P String-

mdlhCw~pzOb@KV\Sd@c@CGK_DZiI|AuH\rdCiNrGi^xQ}HjDkFf@_IyTf@mKNm@H}C]

O/P String-

mdlhCw~pzOb@KV\Sd@c@CGK_DZiI|AuH\tdCiNrGi^xQ}HjDkFf@_IyTf@mKNm@H}C]

So, here I am escaping the '\' before 'S' but not the '\' before 't'. Other than brute force by checking for every possible scenario, is there any other way to doe that ?

Sudip
  • 647
  • 2
  • 7
  • 28
  • I think you need to escape only in specific cases and not always – Ori Marko Aug 03 '17 at 06:52
  • `str.replace("\\", "\\\\").replace("\\\\n","\\n").replace("\\\\t","\\t) ...` What about that ? – Asew Aug 03 '17 at 06:55
  • Why? What is the reason you need to do this? – user207421 Aug 03 '17 at 07:15
  • @EJP I need to send this big string to the server from my android app. Now while sending it, I was previously escaping all the '\' characters (otherwise, they couldn't be sent via http) Now, I have this issue because of which the decoded string doesn't work at all. – Sudip Aug 03 '17 at 07:19
  • But, isn't "\\" always a backlash not escaping anything ? `\n`, `\r`, `\t` etc are characters, and not a '\\' followed by a letter. How is your String formed to have "\\r" that need to be interpreted as "\r" ? – Jeremy Grand Aug 03 '17 at 07:25

1 Answers1

0

use the String.replaceAll method, which accepts a regular expression as an input to find strings to replace.

Place a regular expression that matches all backslashes, except those that have your blacklisted character next to it.

albert_nil
  • 1,648
  • 7
  • 9