[英]how do i replace any string with a “$ ” in java?
使用replaceAll()
给了我一个 rexex 异常。
这是我正在使用的代码:
public class test {
public static void main(String[] args) {
String text= "This is to be replaced &1 ";
text = text.replaceAll("&1", "&");
System.out.println(text);
}
}
例外:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at test.main(test.java:7)
似乎对我来说工作得很好。 http://ideone.com/7qR6Z
但是对于这么简单的事情,您可以避免使用正则表达式,只需使用string.replace()
text = text.replace("&1", "&");
如果您不想要正则表达式,请使用String#replace方法,如下所示:
"This is to be replaced &1 ".replace("&1", "&")
我在替换为“$”符号时解决此错误的方法是将所有“$”替换为“\\$”,如下面的代码所示:
myString.replaceAll("\\$", "\\\\\\$");
您可以使用 Pattern.quote() 将任何字符串编译为正则表达式。 尝试:
public class test {
public static void main(String[] args) {
String text= "This is to be replaced &1 ";
text = text.replaceAll(Pattern.quote("&1"), "&");
System.out.println(text);
}
}
就目前而言,您的代码工作正常。 但是,如果您输入错误或其他内容并且实际上有
text = text.replaceAll("&1", "$");
然后你必须逃避替换:
text = text.replaceAll("&1", "\\$");
您的问题标题显示how do i replace any string with a “$ ” in java?
但你的问题文本说String text= "This is to be replaced &1 "
如果您实际上是在尝试替换美元符号,这是正则表达式中的特殊字符,您需要使用反斜杠对其进行转义。 您需要转义该反斜杠,因为 blackslash 是 Java 中的特殊字符,因此假设美元符号是您想要的:
String text = "This is to be replaced $1 ";
text = text.replaceAll("\\$1", "\\$");
System.out.println(text);
编辑:澄清一些文字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.