String.replaceAll single backslashes with double backslashes
Solution 1:
The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
Solution 2:
TLDR: use theString = theString.replace("\\", "\\\\");
instead.
Problem
replaceAll(target, replacement)
uses regular expression (regex) syntax for target
and partially for replacement
.
Problem is that \
is special character in regex (it can be used like \d
to represents digit) and in String literal (it can be used like "\n"
to represent line separator or \"
to escape double quote symbol which normally would represent end of string literal).
In both these cases to create \
symbol we can escape it (make it literal instead of special character) by placing additional \
before it (like we escape "
in string literals via \"
).
So to target
regex representing \
symbol will need to hold \\
, and string literal representing such text will need to look like "\\\\"
.
So we escaped \
twice:
- once in regex
\\
- once in String literal
"\\\\"
(each\
is represented as"\\"
).
In case of replacement
\
is also special there. It allows us to escape other special character $
which via $x
notation, allows us to use portion of data matched by regex and held by capturing group indexed as x
, like "012".replaceAll("(\\d)", "$1$1")
will match each digit, place it in capturing group 1 and $1$1
will replace it with its two copies (it will duplicate it) resulting in "001122"
.
So again, to let replacement
represent \
literal we need to escape it with additional \
which means that:
- replacement must hold two backslash characters
\\
- and String literal which represents
\\
looks like"\\\\"
BUT since we want replacement
to hold two backslashes we will need "\\\\\\\\"
(each \
represented by one "\\\\"
).
So version with replaceAll
can look like
replaceAll("\\\\", "\\\\\\\\");
Easier way
To make out life easier Java provides tools to automatically escape text into target
and replacement
parts. So now we can focus only on strings, and forget about regex syntax:
replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))
which in our case can look like
replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
Even better
If we don't really need regex syntax support lets not involve replaceAll
at all. Instead lets use replace
. Both methods will replace all target
s, but replace
doesn't involve regex syntax. So you could simply write
theString = theString.replace("\\", "\\\\");