5
A
回答
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");
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 {
0
注意第一个给定的参数是不是你想要替换字符串。这是一个正则表达式。您可以尝试构建一个正则表达式,以匹配要替换的字符串on this site。
special = special.replaceAll("\\@\\$", "as");
会的工作,通过@Mritunjay
2
方法的replaceAll接受正则表达式作为一个模式来substitue的建议: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
尝试简单:
special = special.replace("@$", "as");
0
special = special.replaceAll("\\W","as");
作品与所有特殊字符。
你想要做字符串插值,或者这个例子看起来像这样吗?如果是这样,请看[MessageFormat](https://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html) –