2011-05-27 74 views
0

使用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) 
+4

在Java 1.6上编译和运行此代码不会产生异常... – maerics 2011-05-27 18:42:06

+0

我运行了代码,运行良好。 – 2011-05-27 18:42:21

+2

按照惯例,Java类的第一个字母必须用大写字母写在这种情况下测试 – Bartzilla 2011-05-27 18:44:22

回答

4

似乎为我工作的罚款。 http://ideone.com/7qR6Z

不过的东西这个简单,你能避免正则表达式,只需使用string.replace()

text = text.replace("&1", "&"); 
+0

非常感谢,这是我的一个简单的误解。 – tasa 2011-05-27 18:49:33

+0

'String.replace()'只接受字符作为参数。 http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html – Marcelo 2011-05-27 22:10:54

+0

@Marcelo还有另一个需要字符串的charsequence。 – 2011-05-28 00:21:11

2

如果你不想正则表达式,然后使用String#replace方法,而不是像这样:

"This is to be replaced &1 ".replace("&1", "&") 
0

因为它你的代码工作正常。但是,如果错误或东西,其实有

text = text.replaceAll("&1", "$"); 

那么你就不得不逃离更换:

text = text.replaceAll("&1", "\\$"); 
1

您可以使用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); 
    } 
} 
0

你的问题的标题显示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);

编辑:澄清一些文字

2

我替换为“$”符号时出现此错误的解决方案是用“\\ $”替换所有“$”,如下面的代码所示:

myString.replaceAll("\\$", "\\\\\\$");