3

I am writing some simple java code that looks in a string to find a value called REPLACEALL. Once it finds that string I have it replace it with a path name as a value (ex:D:\test\path\something). However, when I run the code it replace it fine but it removes the single \. I am not sure why and have set up a debug to see where it is happening. The original string gets passed in fine, its only when the string goes through the replaceAll() that it causes this issue.

Java:

String path = "D:\test\path\something";
String s1="select * from Webserver WHERE data= REPLCAEME";  
String replaceString=s1.replaceAll("REPLACEME"," ' " + path + " ' ");  
System.out.println(replaceString);  
kane_004
  • 253
  • 3
  • 18
  • 4
    Does this answer your question? [What is the backslash character (\\‌)?](https://stackoverflow.com/questions/12091506/what-is-the-backslash-character) – lugiorgi Feb 14 '20 at 12:42
  • 1
    Have you tried escaping your backslashes with `\\`? – Billy Brown Feb 14 '20 at 12:42
  • @BillyBrown I can't modify the string, its preset by an api and passed straight into the application to get replaced. So that's why I am having a hard time solving the issue – kane_004 Feb 14 '20 at 12:46
  • 3
    It seems you want to build up an SQL statement. In this case, this is anyhow the wrong approach. Have a look to `PreparedStatement`. – Henry Feb 14 '20 at 12:47
  • @lugiorgi Somewhat, but as I mentioned just a few minute ago in the comments, I can't access the string contents, it is passed from an API and I pass it straight through to the replaceAll() method. Unless....is there a way to add an extra backslash to the string before I pass it? – kane_004 Feb 14 '20 at 12:49
  • @Henry Not sure if I follow, I already have the SQL statement that only has half of the query done. So when the user selects an option in the front-end it replaces the placeholder in the SQL query with the proper value. – kane_004 Feb 14 '20 at 12:51
  • 1
    @kane_004 and this is exactly the use case PreparedStatements are intended to solve. They also take care of SQL injection problems. – Henry Feb 14 '20 at 12:53
  • What if we're not fetching data via an api? We won't be able to use PreparedStatements then? – mikasa Oct 03 '22 at 04:41

1 Answers1

4

The backslash is used as an escape character in strings, which means that you have to escape it itself as \\. Otherwise, it denotes special characters, e.g., \t denotes a tab space, so in your example \test effectively means <tab>est.

pxcv7r
  • 478
  • 5
  • 14