On escape sequences
A declaration like:
String s = "\\";
defines a string containing a single backslash. That is, s.length() == 1
.
This is because \
is a Java escape character for String
and char
literals. Here are some other examples:
"\n"
is a String
of length 1 containing the newline character
"\t"
is a String
of length 1 containing the tab character
"\""
is a String
of length 1 containing the double quote character
"\/"
contains an invalid escape sequence, and therefore is not a valid String
literal
- it causes compilation error
Naturally you can combine escape sequences with normal unescaped characters in a String
literal:
System.out.println("\"Hey\\\nHow\tare you?");
The above prints (tab spacing may vary):
"Hey\
How are you?
References
See also
Back to the problem
Your problem definition is very vague, but the following snippet works as it should:
System.out.println("How are you? Really??? Awesome!".replace("?", "\\?"));
The above snippet replaces ?
with \?
, and thus prints:
How are you\? Really\?\?\? Awesome!
If instead you want to replace a char
with another char
, then there's also an overload for that:
System.out.println("How are you? Really??? Awesome!".replace('?', '\\'));
The above snippet replaces ?
with \
, and thus prints:
How are you\ Really\\\ Awesome!
String
API links
On how regex complicates things
If you're using replaceAll
or any other regex-based methods, then things becomes somewhat more complicated. It can be greatly simplified if you understand some basic rules.
- Regex patterns in Java is given as
String
values
- Metacharacters (such as
?
and .
) have special meanings, and may need to be escaped by preceding with a backslash to be matched literally
- The backslash is also a special character in replacement
String
values
The above factors can lead to the need for numerous backslashes in patterns and replacement strings in a Java source code.
It doesn't look like you need regex for this problem, but here's a simple example to show what it can do:
System.out.println(
"Who you gonna call? GHOSTBUSTERS!!!"
.replaceAll("[?!]+", "<$0>")
);
The above prints:
Who you gonna call<?> GHOSTBUSTERS<!!!>
The pattern [?!]+
matches one-or-more (+
) of any characters in the character class [...]
definition (which contains a ?
and !
in this case). The replacement string <$0>
essentially puts the entire match $0
within angled brackets.
Related questions
Regular expressions references