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); 
8
  • 4
    Does this answer your question? What is the backslash character (\\‌)? Commented Feb 14, 2020 at 12:42
  • 1
    Have you tried escaping your backslashes with `\`? Commented Feb 14, 2020 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 Commented Feb 14, 2020 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. Commented Feb 14, 2020 at 12:47
  • 1
    @kane_004 and this is exactly the use case PreparedStatements are intended to solve. They also take care of SQL injection problems. Commented Feb 14, 2020 at 12:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.