【问题标题】:replaceAll type method that preserves special characters保留特殊字符的replaceAll类型方法
【发布时间】:2012-08-16 09:07:52
【问题描述】:

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

我遇到的问题是我传递给这两种方法的替换字符串包含一个美元符号(这在正则表达式中当然具有特殊含义)。一个简单的解决方法是将我的替换字符串传递给“Matcher.quoteReplacement”,因为这会产生一个带有文字字符的字符串,然后将此 sanitized 字符串传递给replaceAll

不幸的是,我无法执行上述操作,因为我需要保留特殊字符,因为生成的字符串稍后将用于需要 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).

【问题讨论】:

  • 我不确定您的问题是什么。你能不能把matcher.quoteReplacement 的结果保存到一个临时变量中,你只在正则表达式中使用一次?如果你能提供一个代码示例会更清楚。

标签: java regex string


【解决方案1】:

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

【讨论】:

  • 谢谢你,anubhava - 我很尴尬我错过了这么明显的东西!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2011-05-08
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 2014-02-10
相关资源
最近更新 更多