jn025
jn025

Reputation: 2895

Java back slash character not being output in string

I'm trying to replace some text in a file and the string contains a file path which requires some back slashes, normally using "\" works fine and produces a single \ on the output but my current code is not outputting any backslashes

String newConfig = readOld().replaceAll(readOld(),"[HKEY_CURRENT_USER\\Software\\xxxx\\xxxx\\Config]");

Upvotes: 0

Views: 103

Answers (2)

Akash Thakare
Akash Thakare

Reputation: 22972

You should use replace here as it may possible your readOld() method may be having some special characters (i.e +,*,. etc.) which are reserved in regExp so better to use replace.(As replaceAll may throw Exception for invalid regular Expression)

String newConfig = readOld().replace(readOld(),"replacement");

As here it seems you are replacing whole String why not just assign String directly to newConfig


From JavaDoc for replaceAll

Backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement String

So either go For \\\\ (As suggested by Elliott Frinch) in String or use replace.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

The "\" starts an escape sequence,

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.

So, (ludicrously perhaps)

String old = readOld();
String newConfig = old.replaceAll(old,
    "[HKEY_CURRENT_USER\\\\Software\\\\xxxx\\\\xxxx\\\\Config]");

Or,

String old = readOld();
char backSlash = '\\';
String newConfig = old.replaceAll(old,
    "[HKEY_CURRENT_USER" + backSlash + backSlash + "Software"
    + backSlash + backSlash + "xxxx"
    + backSlash + backSlash + "xxxx"
    + backSlash + backSlash + "Config]");

Upvotes: 2

Related Questions