replaceAll does not replace string [duplicate]

主宰稳场 提交于 2019-11-28 01:58:20
Thierry-Dimitri Roy

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.

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.

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!