Java替换特殊字符

Jam*_*mmy 5 java

我试图用一个只有特殊字符的模式替换文件中的特殊字符,但它似乎不起作用.

String special = "Something @$ great @$ that.";
special = special.replaceAll("@$", "as");
Run Code Online (Sandbox Code Playgroud)

但是,当我运行时,我得到原始字符串而不是替换字符串.我究竟做错了什么?

Nic*_*tto 7

只需String#replace(CharSequence target, CharSequence replacement)在您的情况下使用替换给定的CharSequence,如下:

special = special.replace("@$", "as");
Run Code Online (Sandbox Code Playgroud)

或者用于Pattern.quote(String s)将您String的文本模式转换String为下一个:

special = special.replaceAll(Pattern.quote("@$"), "as");
Run Code Online (Sandbox Code Playgroud)

如果您打算非常频繁地执行此操作,请考虑重用相应的Pattern实例(该类Pattern是线程安全的,这意味着您可以共享此类的实例),以避免在每次调用时编译正则表达式,这些调用具有性能方面的价格.

所以你的代码可能是:

private static final Pattern PATTERN = Pattern.compile("@$", Pattern.LITERAL);
...
special = PATTERN.matcher(special).replaceAll("as");
Run Code Online (Sandbox Code Playgroud)


Mri*_*jay 5

逃脱字符: -

    String special = "Something @$ great @$ that.";
    special = special.replaceAll("@\\$", "as");
    System.out.println(special);
Run Code Online (Sandbox Code Playgroud)

对于正则表达式,保留低于12个字符称为元字符.如果要将这些字符中的任何一个用作正则表达式中的文字,则需要使用反斜杠转义它们.

the backslash \
the caret ^
the dollar sign $
the period or dot .
the vertical bar or pipe symbol |
the question mark ?
the asterisk or star *
the plus sign +
the opening parenthesis (
the closing parenthesis )
the opening square bracket [
and the opening curly brace {
Run Code Online (Sandbox Code Playgroud)

参考文献: - http://www.regular-expressions.info/characters.html