我对Java字符串的replaceAll函数有疑问
replaceAll("regex", "replacement");
工作正常,但每当我的“替换”字符串包含像“$0”、“$1”等子字符串时,它就会通过用相应的匹配组替换这些 $x 来产生问题。
例如
input ="NAME";
input.replaceAll("NAME", "HAR$0I");
将生成字符串“HARNAMEI”,因为替换字符串包含“$0”,该字符串将被匹配组“NAME”替换。我怎样才能超越这种本性。我只需要获取结果字符串“HAR$0I”。
我转义了 $ 。即我将替换字符串转换为“HAR\\$0I”,效果很好。但我正在寻找 java 中的任何方法,可以为我对所有这些在正则表达式世界中具有特殊含义的字符执行此操作。
最佳答案
java.lang.String.replaceAll() 的文档说:
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.
String quoteReplacement(String s) 的文档说:
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.
关于java - 正则表达式匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067733/