|
Java FAQ: Why isn't my replace, replaceAll, or replaceFirst code working?
The Java String class has several methods that usually make it really easy to replace one text pattern with another. I say "usually" because what often happens is that I usually forget that a String is immutable, so I first try some replace, replaceAll, or replaceFirst code that looks like this:
// this won't work
currentString.replaceAll("<", "<");
and then I wonder why the replace/replaceAll/replaceFirst method isn't working.
Of course it is working, I just need to use it properly, like this:
// this is the correct use
currentString = currentString.replaceAll("<", "<");
Hopefully the difference in those two examples is apparent. In the first example I'm calling the replaceAll method on my String object, hoping that String will somehow be changed. (After all these years it still won't, because it's immutable.)
In the second example I'm doing the correct thing, calling the replaceAll method on my currentString object, then assigning that result back to my currentString reference.
Technically the new currentString reference is pointing to a new String object in memory, but the important thing is that this is the correct way to use the replace, replaceAll, and replaceFirst methods -- assign the result to a new String reference, then use that reference.
|