replaceAll does not replace string [duplicate]
Asked Answered
T

3

7

I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?

private String buildQuery(){
    String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

    deserializeQuotes();

    StringBuffer symbols = new StringBuffer();
    for(int i = 0; i < quotes.size();i++){
        if(i == (quotes.size()-1))
            symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
        else
            symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
    }

    System.out.println("***SYMBOLS***" + symbols.toString());
    query.replaceAll("REPLACEME", symbols.toString());

    return query;
}
Twerp answered 31/8, 2010 at 17:36 Comment(0)
R
19

Change

query.replaceAll("REPLACEME", symbols.toString());

to:

query = query.replaceAll("REPLACEME", symbols.toString());

Strings in Java are designed to be immutable.
That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.


Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others.

Reinareinald answered 31/8, 2010 at 17:38 Comment(2)
Also note, strings are immutable in Java. You can NEVER change a string in place.Tuttle
I always forget this xDNuclei
G
6

Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.

Guib answered 31/8, 2010 at 17:38 Comment(0)
H
5

The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this:

query = query.replaceAll("REPLACEME", symbols.toString());
Haiku answered 31/8, 2010 at 17:38 Comment(1)
+1 for mentioning the immutability of String.Scattering

© 2022 - 2024 — McMap. All rights reserved.