简体   繁体   中英

how do i replace any string with a “$ ” in java?

Using replaceAll() is giving me a rexex exception.

This is the code I am using:

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:

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)

Seems to work fine for me. http://ideone.com/7qR6Z

But for something this simple, you can avoid regex and just use string.replace()

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

If you don't want regex then use String#replace method instead like this:

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

My solution for this error while replacing with "$" sign was to replace all "$" with "\\$" like in code bellow:

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

You can use Pattern.quote() to compile any string into a regular expression. Try:

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);   
    }
}

As it stands, your code works fine. However, if you mistyped or something and actually have

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

Then you DO have to escape the replacement:

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

Your question title shows how do i replace any string with a “$ ” in java? but your question text says String text= "This is to be replaced &1 "

If you're actually trying to replace a dollar sign, this is a special character in regular expressions, you need to escape it with a backslash. You need to escape that backslash, because blackslash is a special character in Java, so assuming dollar sign is what you intended:

String text = "This is to be replaced $1 ";

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

System.out.println(text);

EDIT: Clarify some text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM