我尝试使用只包含特殊字符的模式替换文件中的特殊字符,但似乎并没有起作用。
String special = "Something @$ great @$ that.";
special = special.replaceAll("@$", "as");
然而,当我运行它时,我得到的是原始字符串,而不是替换后的字符串。我做错了什么?
我尝试使用只包含特殊字符的模式替换文件中的特殊字符,但似乎并没有起作用。
String special = "Something @$ great @$ that.";
special = special.replaceAll("@$", "as");
在您的情况下,只需使用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");
转义字符:-
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 {
这篇文章涉及IT技术相关内容,提供了一个有用的网站链接,该网站详细介绍了正则表达式中各种字符的含义。请参考上述链接以获取更多信息。special = special.replace("@$", "as");
special = special.replaceAll("\\W","as");
适用于所有特殊字符。
String special = "Something @$ great @$ that.";
System.out.println(special.replaceAll("[@][$]", "as"));
special = special.replaceAll("\\@\\$", "as");
可以工作。