Strings in Java are immutable, which makes this a bit complicated if you are talking about an arbitrary number of things that you need to find and replace.
In particular, you need to define your replacements in Map , use StringBuilder (before Java 9 you should use a less efficient StringBuffer ) and the appendReplacements() and appendTail() methods from Matcher . The final result will be saved in your StringBuilder (or StringBuffer ).
Map<String, String> replacements = new HashMap<String, String>() {{ put("${env1}", "1"); put("${env2}", "2"); put("${env3}", "3"); }}; String line ="${env1}sojods${env2}${env3}"; String rx = "(\\$\\{[^}]+\\})"; StringBuilder sb = new StringBuilder();
Exit:
1sojods23
source share