replaceAll类型方法,保留特殊字符

时间:2012-08-16 09:07:53

标签: java regex string

目前,replaceAll类的String方法以及Matcher.replaceAll方法将其参数评估为正则表达式。

我遇到的问题是我传递给这些方法中的任何一个的替换字符串都包含一个美元符号(当然在正则表达式中有特殊含义)。一个简单的解决方法是将我的替换字符串传递给'Matcher.quoteReplacement',因为这会生成一个带有文字字符的字符串,然后将此已清理的字符串传递给replaceAll。< / p>

不幸的是,我无法执行上述操作,因为我需要保留特殊字符,因为后来在预期使用reg ex的操作中使用了结果字符串,如果我已经转义了所有特殊字符,那么这将破坏该合同

有人可以建议我可以实现我想做的事情吗?非常感谢。

编辑:有关更清楚的解释,请在下面找到代码示例:

String key = "USD";
String value = "$";

String content = "The figure is in USD";
String contentAfterReplacement;

contentAfterReplacement = content.replaceAll(key, value); //will throw an exception  as it will evaluate the $ in 'value' variable as special regex character

contentAfterReplacement = content.replaceAll(key, Matcher.quoteReplacement(value)); //Can't do this as contentAfterReplacement is passed on and later parsed as a regex (Ie, it can't have special characters escaped).

1 个答案:

答案 0 :(得分:2)

为什么不使用String#replace方法而不是replaceAllreplaceAll使用正则表达式,但replace不在替换字符串中使用正则表达式。

相关问题