我需要更换
\\\s+\\$\\$ to $$
我用了
String s = " $$";
s = s.replaceAll("\\s+\\$\\$","$$");
但它引发异常
java.lang.IllegalArgumentException:非法的组引用
我需要更换
\\\s+\\$\\$ to $$
我用了
String s = " $$";
s = s.replaceAll("\\s+\\$\\$","$$");
但它引发异常
java.lang.IllegalArgumentException:非法的组引用
Answers:
使用"\\$\\$"
第二个参数:
String s=" $$";
s=s.replaceAll("\\s+\\$\\$","\\$\\$");
//or
//s=s.replaceAll("\\s+\\Q$$\\E","\\$\\$");
$
正则表达式的替换参数中的is组符号
所以你需要逃脱它
请注意,替换字符串中的反斜杠(\)和美元符号($)可能导致结果与被视为文字替换字符串时的结果不同;请参阅Matcher.replaceAll。如果需要,请使用Matcher.quoteReplacement(java.lang.String)取消显示这些字符的特殊含义。
因此,可以使用Matcher#quoteReplacement来转义任意替换字符串:
String s = " $$";
s = s.replaceAll("\\s+\\$\\$", Matcher.quoteReplacement("$$"));
也可以使用Pattern#quote来转义模式
String s = " $$";
s = s.replaceAll("\\s+" + Pattern.quote("$$"), Matcher.quoteReplacement("$$"));
String.replaceAll(regexp, replacement)
并未证明它会将替换String当作幕后的正则表达式处理。作为一名程序员,我可能会对使用regexp进行匹配感兴趣,而对于使用文字进行替换感兴趣-如果API文档中没有相应的提示,我希望这会发生。
String
,只是没有在第一行。对不起,我的缺点。
我遇到了同样的问题,所以我最终用split替换了全部。
它为我解决了例外
public static String replaceAll(String source, String key, String value){
String[] split = source.split(Pattern.quote(key));
StringBuilder builder = new StringBuilder();
builder.append(split[0]);
for (int i = 1; i < split.length; i++) {
builder.append(value);
builder.append(split[i]);
}
while (source.endsWith(key)) {
builder.append(value);
source = source.substring(0, source.length() - key.length());
}
return builder.toString();
}
replaceFirst()
。以下答案也有帮助。