Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string exactly as it is?

Tags:

java

Consider the following code:

String str = "folder1;b";
String replacement = "C:\\myfolder";
System.out.println(str.replaceAll("b", replacement));

This printsC:myfolder.
How can I replace str with the replacement string as is? (Without the slashes being removed)
I've tried Pattern.quote(replacement) but that prints \QC:\Development\E

I have no control over replacement which comes from an external source and it is not known what its contents would be.

like image 234
user7436452 Avatar asked Jun 04 '26 21:06

user7436452


1 Answers

If you aren't using regular expressions, better to use String.replace():

String str = "folder1;b";
String replacement = "C:\\myfolder";
System.out.println(str.replace("b", replacement));

String.replace() does a literal replacement, it doesn't treat the arguments as regular expressions.

I will point out that you will run into trouble if your str is folder1;bash;b as both of the bs will be replaced.