使用StringSubstitutor时如何解决悬挂${导致的变量未替换问题?
测试用例
// 构建映射表 Map<String, String> 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); assertThat( resolvedString, is( "The quick brown fox jumped ${ over the lazy dog.%") );
失败情况
${target}变量未被替换:
java.lang.AssertionError: Expected: is "The quick brown fox jumped ${ over the lazy dog.%" but: was "The quick brown fox jumped ${ over the ${target}.%"
问题原因与修复
问题出在模板字符串里的${ (带有空格的占位符起始),StringSubstitutor会将其判定为未闭合的变量占位符,后续的${target}会被视作这个未完成占位符的一部分,无法被独立识别替换。
修复方式:
- 要输出字面量
${,需用反斜杠转义,调整模板字符串:
String templateString = "The ${animal} jumped \\${ over the ${target}.%";
StringSubstitutor默认转义字符为\,无需额外配置,转义后${会被保留为普通文本,${target}就能正常替换为lazy dog,断言可通过。
内容的提问来源于stack exchange,提问作者Ian Lim
相关产品推荐
相关产品推荐

