0

In Java am trying to use replaceAll as follows:

String inspect;
inspect = "Hello & goodbye&otherstuff";
inspect.replaceAll('&', '~');

I expect to receive "Hello ~ Goodbye~otherstuff"

but I always get the original string with no replacements.

Thanks for your advice.

Intrinsic
  • 1
  • 1

2 Answers2

3

If you read the documentation for String.replaceAll, the return value of String.replaceAll is a result String. you need to assign the result value to something in order be able to use it.

so you can use it like this:

inspect = inspect.replaceAll('&', '~');
Popeye
  • 11,839
  • 9
  • 58
  • 91
Pooya
  • 6,083
  • 3
  • 23
  • 43
  • Correct but personally I think you should expand on the answer and example why. – Popeye Apr 11 '16 at 09:35
  • I was in the process of writing my own answer to explain why to do it this way. I have given all credit to you as you answered first but I have provide a description. +1 – Popeye Apr 11 '16 at 09:51
1

Pooya is correct in that you should use

inspect = inspect.replaceAll('&', '~');

However I think their answer lags the reasoning behind why this should be done. So the reason why you have to do this is because when you construct a string, in your case the value of inspect the value of that String is constant and cannot be changed after they are created.

(Unless you are using String buffers that is that support mutable Strings.)

The reason it cannot be changed is because a String Object is in fact immutable.

So what happens when you use inspect.replaceAll('&', '~') is it will actually be using the the method:

public String replaceAll(String regex, String replacement)

See String Documentation for a full description here.

As per the documentation:

Replaces each substring in this string that matches the given regular expression with the given replacement value.

Eventually this method will return a String value, so it will need to place that String value somewhere when it is returned. So the code you have of inspect.replaceAll('&', '~'); doesn't actually place the new String into an object so inspect remains the same. So as per Pooyas answer all you need to do is place it into the object again like:

inspect = inspect.replaceAll('&', '~');
Popeye
  • 11,839
  • 9
  • 58
  • 91