In case you do not want to rely on any third-party library, and you do want to use unnamed, unnumbered placeholders like SLF4j does, like
This {} is a placeholder, and this {} is another one
I came up with this approach:
public static String format(String m, Object... placeholder) {
final int[] counter = {0};
return Pattern.compile("\\{}").matcher(m).replaceAll(matchResult -> {
if (counter[0] == placeholder.length)
throw new RuntimeException("Some placeholder arguments missing for " + m);
return Matcher.quoteReplacement(String.valueOf(placeholder[counter[0]++]));
});
}
It does not validate for unnecessary placeholders, only for missing placeholder arguments. Can be easily added in case you care about that case.
Using Matcher.quoteReplacement
is optional, but in case you are using file paths mandatory. Otherwise slashes will be removed
org.slf4j.helpers.MessageFormatter
The code looks like this:String str = "Hello this is {} string {}"; MessageFormatter.format(str, new String[]{"hello", "world", "blah"}).getMessage();
– Bowles