I have a String like this: "#{var1} is like #{var2}
.
I would like to replace the "#{var1}
and "#{var1}
with the values of variables var1
and var1
. Is there a smart way to do this without iterating over the whole string and finding the pattern #{}
and then replacing it?
I couldn't find a library that would do that.

- 3,841
- 2
- 37
- 63

- 1,494
- 1
- 19
- 29
-
1http://stackoverflow.com/questions/2375224/java-library-that-enables-var-substitution (though the question uses ${var} instead of #{var}) – FriedSaucePots Sep 18 '15 at 16:01
-
1possible duplicate of [How to create dynamic Template String](http://stackoverflow.com/questions/2368802/how-to-create-dynamic-template-string) <-- Has a [great answer](http://stackoverflow.com/a/2368810/119775) – Jean-François Corbett Sep 18 '15 at 16:23
-
Is there a reason not to use [String.replace](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-)? – VGR Sep 18 '15 at 17:33
3 Answers
You can use a the java buildin regular expression mechanism to find the pattern in the inspected string and make the replacement using the proper functions. Let me show you...
public static void main(String[] args)
{
StringBuilder output = new StringBuilder();
String inputString = "sequence to analize #{var1} is like #{var2}";
Pattern pattern = Pattern.compile("#\\{(.*?)\\}");
Matcher matcher = pattern.matcher(inputString);
int lastStart = 0;
while (matcher.find()) {
String subString = inputString.substring(lastStart,matcher.start());
String varName = matcher.group(1);
String replacement = getVarValue (varName);
output.append(subString).append(replacement);
lastStart = matcher.end();
}
System.out.println(output.toString());
}
private static String getVarValue(String varName) {
return "value"; // do what you got to replace the variable name for its value
}
Perhaps the example needs to be worked a little more.. but it can give you an idea.
Hope it Helps.
Greetings.

- 3,841
- 2
- 37
- 63
-
Must add more line `output.append(inputString.substring(lastStart));` after the while loop. – Duy Banh Oct 01 '21 at 16:18
Probably the easiest way to achieve this is using String.format
. It internally uses the Formatter
class.
This approach has the beauty you don't need any third party library (String.format
was introduced with Java 1.5).
Here a complete example:
import static java.lang.String.format;
public class Interpolate {
public static void main(String[] args) {
String var1 = "foo";
String var2 = "bar";
String s = format("%1$s is like %2$s is like %1$s",var1, var2);
System.out.println(s); // "foo is like bar is like foo"
}
}
Notice the numbers in %1$s
or %2$s
. They refer to the position of the parameters in the format call. This allows you to use the variable multiple times and you can rearrange the order of the variables freely (within the format string).
For more info on the format string see the Formatter documentation.

- 311
- 1
- 9