0

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?

4

6 回答 6

3

Try this: You have to use escape character '\'

text = text.replaceAll("\\\\", "%5C");
于 2013-04-11T14:13:15.637 回答
3

尝试

text = text.replaceAll("\\\\", "%5C");

replaceAll使用正则表达式语法 where\是特殊字符,因此您需要对其进行转义。为此,您需要传递\\给正则表达式引擎,但要创建表示正则表达式的字符串,\\您需要将其写为"\\\\"\也是 String 中的特殊字符,每个都需要另一个转义\


为了避免这种正则表达式混乱,您可以使用replace正在处理文字的

text = text.replace("\\", "%5C");
于 2013-04-11T14:17:24.357 回答
2

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");

于 2013-04-11T14:13:08.433 回答
2

第一个参数 toreplaceAll被解释为正则表达式,因此您实际上需要四个反斜杠:

text = text.replaceAll("\\\\", "%5C");

字符串文字中的四个反斜杠表示实际中的两个反斜杠String,这反过来表示匹配单个反斜杠字符的正则表达式。

或者,按照Pshemo的建议,使用replace而不是,它将其第一个参数视为文字字符串而不是正则表达式。replaceAll

于 2013-04-11T14:13:57.340 回答
1

首先,由于“\”是 Java 中的转义字符,因此您需要使用两个反斜杠来获得一个反斜杠。其次,由于 replaceAll() 方法将正则表达式作为参数,因此您还需要转义该反斜杠。因此,您需要使用

text = text.replaceAll("\\\\", "%5C");
于 2013-04-11T14:14:25.863 回答
0

我可能会迟到,但并非最不重要。

添加\\\\以下正则表达式以启用\.

示例正则表达式:

private val specialCharacters = "-@%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_\\\\"
private val PATTERN_SPECIAL_CHARACTER = "^(?=.*[$specialCharacters]).{1,20}$"

希望能帮助到你。

于 2019-08-13T11:57:34.057 回答