Java 模板变量替换——字符串替换器
说明
- 这里分享 3 种方法,从功能最强大的开始
可选方法
org.apache.commons.text
- 参考文档:https://commons.apache.org/proper/commons-text/javadocs/api-release/index.html
- 代码:
Map valuesMap = new HashMap(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StringSubstitutor sub = new StringSubstitutor(valuesMap); String resolvedString = sub.replace(templateString);
- 输出:
The quick brown fox jumped over the lazy dog.
- 可以为变量设置默认值,格式为:
${undefined.number:-1234567890}
,其中undefined.number
是变量名,:-
是分隔符,1234567890
是默认值。 - 代码:
Map valuesMap = new HashMap(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}."; StringSubstitutor sub = new StringSubstitutor(valuesMap); String resolvedString = sub.replace(templateString);
- 输出:
The quick brown fox jumped over the lazy dog. 1234567890.
java.text.MessageFormat
- 代码:
Object[] params = new Object[]{"hello", "!"}; String msg = MessageFormat.format("{0} world {1}", params);
- 输出:
hello world!
java.lang.String
- 代码:
String s = String.format("My name is %s. I am %d.", "Andy", 18);
- 输出:
My name is Andy. I am 18.