2011-05-27 62 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("\\$", "\\\\\\$");