正则表达式Java字符串ReplaceAll和ReplaceFirst在替换文本处的$Symbol处失败
我写了这段代码:
public static void main(String args[]) throws Exception {
String template = "The user has spent amount in a day";
String pattern = "amount";
String output = template.replaceAll(pattern, "$ 100");
System.out.println(output);
}
这是我运行它时发生的情况:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Matcher.java:713)
at java.util.regex.Matcher.replaceAll(Matcher.java:813)
at java.lang.String.replaceAll(String.java:2190)
at demo.BugDemo.main(BugDemo.java:16)
Java Result: 1
我正在从文件中读取数据。我应该转义文件数据中的所有$
符号,还是这是一个不必要的过程?是否有其他类或库来处理这种情况
在替换文本(而不是正则表达式)中使用特殊符号有什么问题
注:
我不想检查每个角色来逃避。这就是我问这个问题的原因
我正在使用Java6
# 1 楼答案
特殊字符
$
的处理方法很简单。 检查下面的例子输出:
# 2 楼答案
$
用于指定替换组的符号。你需要逃离它:# 3 楼答案
^{} 将正则表达式匹配模式作为其第一个参数,正则表达式替换模式作为其第二个参数,
$
在正则表达式中具有特定的含义(在匹配模式和替换模式中,尽管意义不同)只要用^{} 来代替,我怀疑你所有的问题都会消失。只有在真正希望通过正则表达式匹配/替换时才应该使用^{,我认为在这种情况下不会这样做
编辑:关于你的问题:
同样,关于
replaceAll
的文档清楚地说明了这一点:因此,如果您想将匹配模式视为正则表达式,而不是替换,那么使用
Matcher.quoteReplacement
# 4 楼答案
试试这个
# 5 楼答案
在替换字符串中,
$
是一个特殊字符:用于从要替换的模式中获取匹配的组。你可以阅读更多关于它的内容要解决这个问题,您可以引用替换字符串来删除
$
字符中的所有特殊含义: