Java: replaceAll not working with backslash?

I am trying to replace the beginning of a line with backslashes with something else. For some strange reason, the replaceAll function doesn't look like a backslash.

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\xyz\\abc", "z:");

What should I do to solve this problem.

Thank.

+1
source share
9 answers

You need to double each backslash (again) since the Pattern class, which is used by replaceAll (), treats it as a special character:

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");

Java string handles backslash as the escape-character, so replaceAll sees \\\\xyz\\abc. But replaceAll also treats the backslash as an escape character, so the regex becomes a character:\ \ x y z \ a b c

+3
source

, \ escape- C- ( ). seperator, , MS-DOS...

, \, \\host\path \\\\host\\path , : P \\\\\\\\host\\\\path

,

String jarPath = "//xyz/abc/wtf/lame/";
jarPath = jarPath.replaceAll("//xyz/abc", "z:");
+3

replaceAll() , escape-. , Java String escape-. , , , :

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
+2

replaceAll , . - escape , , . , "\", ' "\" `.

"\\\\xyz\\abc", "\\\\\\\\xyz\\\\abc" ( \ \):

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
+2
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");

"\" "\\" replaceAll.

+1

replaceAll , , . String.replace :

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replace("\\\\xyz\\abc", "z:");
+1

replace replaceAll . , .

0

replace(), \\\\xyz\\abc String

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replace("\\\\xyz\\abc", "z:");
0

.

() replaceAll, , , Matcher.

String assetPath="\Media Database\otherfolder\anotherdeepfolder\finalfolder";

String assetRemovedPath=assetPath.replaceAll("\\\\Media Database(.*)", Matcher.quoteReplacement("\\Media Database\\_ExpiredAssets")+"$1");

system.out.println("ModifiedPath:"+assetRemovedPath);

:

\Media Database\_ExpiredAssets\otherfolder\anotherdeepfolder\finalfolder

, !

0

All Articles