簡體   English   中英

如何在 java 中用“$”替換任何字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM