简体   繁体   中英

replaceAll and the ampersand character

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.

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('&', '~');

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 Pooya s answer all you need to do is place it into the object again like:

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

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