1

我对 Java 字符串的 replaceAll 函数有疑问

replaceAll("regex", "replacement");

工作正常,但每当我的“替换”字符串包含“$0”、“$1”等子字符串时,它会通过用相应的匹配组替换这些 $x 来产生问题。

例如

input ="NAME";
input.replaceAll("NAME", "HAR$0I");

将产生一个字符串“HARNAMEI”,因为替换字符串包含“$0”,它将被匹配组“NAME”替换。我怎样才能超越这种性质。我只需要将结果字符串作为“HAR$0I”。

我逃脱了 $ .ie 我将替换字符串转换为“HAR\\$0I”,它工作正常。但是我正在寻找java中的任何方法,它可以为我在正则表达式世界中具有特殊含义的所有此类字符执行此操作。

4

3 回答 3

1

The documentation of java.lang.String.replaceAll() says:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

The documentation of String quoteReplacement(String s) says:

Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

于 2013-04-17T18:50:31.993 回答
0

$ in replacement is special character allowing you to use groups. To make it literal you will need to escape it with \$ which needs to be written as "\\$". Same rule apply for \, since it is special character used to escape $. If you would like to use \ literal in replacement you would also need to escape it with another \, so you would need to write it as \\\\.

To simplify this process you can just use Matcher.quoteReplacement("yourReplacement")).


In case where you don't need to use regular expression you can simplify it even more and use

replace("NAME", "HAR$0I") 

instead of

replaceAll("NAME", Matcher.quoteReplacement("HAR$0I")) 
于 2013-04-17T18:50:50.197 回答
0

听起来您实际上是在尝试替换原始字符串,而根本不使用正则表达式。

您应该简单地调用String.replace(),它会在不使用正则表达式的情况下进行文字替换。

于 2013-04-18T14:33:42.097 回答