If you want to replace only lines with lines, then the code from the second part of my answer would be better
The Java Formatter class does not support the form %(key)s , but instead you can use %index$s where the index is counted from 1 as in this example
System.out.format("%3$s, %2$s, %1s", "a", "b", "c"); // indexes 1 2 3
exit:
c, b, a
So, all you have to do is create some array that will contain the values โโused in the template and change the key names to their corresponding indices (incremented by 1 since the first index used by Formatter is written as 1$ not like 0$ like we expect for array indices).
Here is an example of a method that will do this for you
Using
Map<String, Object> map = new HashMap<>(); map.put("name", "Felix"); map.put("age", 70); String myPattern = "Hi %(emptyKey)s! My name is %(name)s %(name)s and I am %(age)s years old"; System.out.println(format(myPattern, map));
exit:
Hi null! My name is Felix Felix and I am 70 years old
As you can see, you can use the same key several times (in our case name ), and if your card does not contain the key used in your String template (for example, emptyKey ), it will be replaced with null .
The above version is for setting a data type of type s d , etc., but if your data will always be replaced by strings, you can skip String.format(sb.toString(), valuesList.toArray()) and replace all your keys with values โโearlier.
Here is a simpler version that will only accept a card with a key-value relationship <String,String> .
static Pattern stringsPattern = Pattern.compile("%\\(([^)]+)\\)s\\b"); public static String formatStrings(String pattern, Map<String, String> map) { StringBuffer sb = new StringBuffer(); Matcher m = stringsPattern.matcher(pattern); while (m.find()) {