Java替换特殊字符

时间:2016-11-18 09:31:14

标签: java

我正在尝试使用只包含特殊字符的模式替换文件中的特殊字符,但它似乎不起作用。

String special = "Something @$ great @$ that.";
special = special.replaceAll("@$", "as");

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

6 个答案:

答案 0 :(得分:7)

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

special = special.replace("@$", "as");

或使用Pattern.quote(String s)String转换为文字模式String,如下所示:

special = special.replaceAll(Pattern.quote("@$"), "as");

如果您打算经常这样做,请考虑重用相应的Pattern实例(类Pattern是线程安全的,这意味着您可以共享此类的实例)以避免编译您的常规每次通话时的表达,其价格与表现有关。

所以你的代码可能是:

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

答案 1 :(得分:5)

转义字符: -

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

对于正则表达式,保留低于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 {

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

答案 2 :(得分:2)

方法replaceAll接受正则表达式作为替换的模式: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

尝试简单:

special = special.replaceAll("\\@\\$", "as");

答案 3 :(得分:1)

String special = "Something @$ great @$ that.";

System.out.println(special.replaceAll("[@][$]", "as"));

应该是这样。

答案 4 :(得分:0)

请注意,第一个给定参数不是您想要替换的字符串。这是一个正则表达式。您可以尝试构建与要替换的字符串on this site匹配的正则表达式。

[textField setBezeled:NO]; [textField setDrawsBackground:NO]; [textField setEditable:NO]; [textField setSelectable:NO]; 可行,正如@Mritunjay

所建议的那样

答案 5 :(得分:0)

special = special.replaceAll("\\W","as"); 

适用于所有特殊字符。

相关问题