Java替换特殊字符

7

我尝试使用只包含特殊字符的模式替换文件中的特殊字符,但似乎并没有起作用。

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

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

你是想要进行字符串插值,还是只是这个例子看起来像这样?如果是的话,请查看MessageFormat - Balázs Édes
6个回答

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个字符被保留为元字符。如果你想在regex中使用这些字符作为字面量,你需要用反斜杠对它们进行转义。

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

这篇文章涉及IT技术相关内容,提供了一个有用的网站链接,该网站详细介绍了正则表达式中各种字符的含义。请参考上述链接以获取更多信息。

2

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

适用于所有特殊字符。


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

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

应该是这样的。

0
请注意,第一个给定的参数不是你想要替换的字符串。它是一个正则表达式。您可以尝试构建一个与您想要替换的字符串在此站点上匹配的正则表达式。
如@Mritunjay所建议的那样,special = special.replaceAll("\\@\\$", "as");可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接