Reputation: 4471
I'm using StringSubstitutor
to complete strings following a user-defined template such as "I program in ${language}".
Map valuesMap = HashMap();
valuesMap.put("language", "Java");
String templateString = "I program in ${language}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
to give "I program in Java".
This works great, but sometimes the template needs to include some transformation of the replacement variable, most often to convert its case. What I'd really like to do is allow patterns along the lines of "I program in ${language:upper}" or "I program in ${upper(language)}" so that the result from above would be "I program in JAVA"
So my questions are:
StringSubstitutor
already support this (and if so, what''s the syntax)?; otherwiseStringSubstitutor
to support this functionality?; orUpvotes: 1
Views: 4901
Reputation: 2531
This should work:
valuesMap.put("language:lower", "java");
valuesMap.put("language:upper", "JAVA");
You can write a function that makes sure you put both variants into HashMap.
void put(HashMap hashMap, String key, String value) {
hashMap.put(key + ":lower", value.toLowerCase());
hashMap.put(key + ":upper", value.toUpperCase());
}
You can also extend HashMap, like so:
class MyHashMap extends HashMap {
@Override
public Object put(Object key, Object value) {
String strKey = (String)key;
String strValue = (String)value;
super.put(strKey + ":lower", strValue.toLowerCase());
super.put(strKey + ":upper", strValue.toUpperCase());
return strKey;
}
}
And then use it like so:
public static void main(String[] args) {
MyHashMap myHashMap = new MyHashMap();
myHashMap.put("test", "test");
System.out.println(myHashMap.get("test:lower"));
System.out.println(myHashMap.get("test:upper"));
}
Upvotes: 2