2016-11-18 202 views
5

我试图用只有特殊字符的模式替换文件中的特殊字符,但似乎没有工作。Java替换特殊字符

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

+0

你想要做字符串插值,或者这个例子看起来像这样吗?如果是这样,请看[MessageFormat](https://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html) –

回答

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 { 

引用: - http://www.regular-expressions.info/characters.html

0

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

special = special.replaceAll("\\@\\$", "as");会的工作,通过@Mritunjay

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

作品与所有特殊字符。