Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop java replaceAll() from removing backslash?

Tags:

java

string

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);  
like image 576
kane_004 Avatar asked Nov 25 '25 05:11

kane_004


1 Answers

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.

like image 163
pxcv7r Avatar answered Nov 27 '25 19:11

pxcv7r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!