Reputation: 756
I have an android application where I have to find out if my user entered the special character '\' on a string. But i'm not obtaining success by using the string.replaceAll() method, because Java recognizes \ as the end of the string, instead of the " closing tag. Does anyone have suggestions of how can I fix this? Here is an example of how I tried to do this:
private void ReplaceSpecial(String text) {
if (text.trim().length() > 0) {
text = text.replaceAll("\", "%5C");
}
It does not work because Java doesn't allow me. Any suggestions?
Upvotes: 0
Views: 3346
Reputation: 52800
I could be late but not the least.
Add \\\\
following regex to enable \
.
Sample regex:
private val specialCharacters = "-@%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_\\\\"
private val PATTERN_SPECIAL_CHARACTER = "^(?=.*[$specialCharacters]).{1,20}$"
Hope it helps.
Upvotes: 0
Reputation: 124225
Try
text = text.replaceAll("\\\\", "%5C");
replaceAll
uses regex syntax where \
is special character, so you need to escape it. To do it you need to pass \\
to regex engine but to create string representing regex \\
you need to write it as "\\\\"
(\
is also special character in String and requires another escaping for each \
)
To avoid this regex mess you can just use replace
which is working on literals
text = text.replace("\\", "%5C");
Upvotes: 3
Reputation: 95958
text = text.replaceAll("\", "%5C");
Should be:
text = text.replaceAll("\\\\", "%5C");
Why?
Since the backward slash is an escape character. If you want to represent a real backslash, you should use double \
(\\
)
Now the first argument of replaceAll is a regular expression. So you need to escape this too! (Which will end up with 4 backslashes).
Alternatively you can use replace which doesn't expect a regex, so you can do:
text = text.replace("\\", "%5C");
Upvotes: 2
Reputation: 12843
Try this: You have to use escape character '\'
text = text.replaceAll("\\\\", "%5C");
Upvotes: 3
Reputation: 122364
The first parameter to replaceAll
is interpreted as a regular expression, so you actually need four backslashes:
text = text.replaceAll("\\\\", "%5C");
four backslashes in a string literal means two backslashes in the actual String
, which in turn represents a regular expression that matches a single backslash character.
Alternatively, use replace
instead of replaceAll
, as recommended by Pshemo, which treats its first argument as a literal string instead of a regex.
Upvotes: 2
Reputation: 1020
First, since "\" is the escape character in Java, you need to use two backslashes to get one backslash. Second, since the replaceAll() method takes a regular expression as a parameter, you will need to escape THAT backslash as well. Thus you need to escape it by using
text = text.replaceAll("\\\\", "%5C");
Upvotes: 1