Class StrSubstitutor
java.lang.Object
com.sure.tool.util.StrSubstitutor
模板变量替换引擎,参考 Apache Commons Text
StrSubstitutor 的高频子集设计。
支持:可配置定界符(前缀/后缀)、默认值语法 ${key:-default}、可配置转义符
(默认 $,$${ 输出字面 ${)、缺失变量保留占位符原样。
示例:
// 基本替换:缺失变量保留原样,值为 null 渲染为空串
StrSubstitutor.substitute("hello ${name}", Map.of("name", "world"));
// => "hello world"
// 默认值语法:变量缺失时使用默认值
StrSubstitutor.substitute("${env:-prod}", Collections.emptyMap());
// => "prod"
// 自定义定界符
StrSubstitutor.replace("<%name%>", Map.of("name", "sure"), "<%", "%>");
// => "sure"
- Since:
- 1.19.0
- Author:
- suretool
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescription构造替换器,使用默认前缀${}、后缀 {@code }、转义符$。StrSubstitutor(String prefix, String suffix) 构造替换器,使用默认转义符$。StrSubstitutor(String prefix, String suffix, char escapeChar) 构造替换器,自定义定界符与转义符。 -
Method Summary
-
Field Details
-
DEFAULT_PREFIX
-
DEFAULT_SUFFIX
-
DEFAULT_ESCAPE
public static final char DEFAULT_ESCAPE默认转义符- See Also:
-
-
Constructor Details
-
StrSubstitutor
public StrSubstitutor()构造替换器,使用默认前缀${}、后缀 {@code }、转义符$。 -
StrSubstitutor
构造替换器,使用默认转义符$。- Parameters:
prefix- 占位符前缀suffix- 占位符后缀- Throws:
IllegalArgumentException- 前缀或后缀为 null 或空串时抛出
-
StrSubstitutor
构造替换器,自定义定界符与转义符。- Parameters:
prefix- 占位符前缀suffix- 占位符后缀escapeChar- 转义符;传0表示禁用转义- Throws:
IllegalArgumentException- 前缀或后缀为 null 或空串时抛出
-
-
Method Details
-
substitute
-
replace
一行式替换(自定义定界符,默认转义符$)。示例:
String text = StrSubstitutor.replace("<%name%> 你好", Map.of("name", "sure"), "<%", "%>");- Parameters:
template- 模板文本;为 null 时返回 nullvars- 变量映射;为 null 时视为空映射prefix- 占位符前缀suffix- 占位符后缀- Returns:
- 替换结果
- Throws:
IllegalArgumentException- 前缀或后缀为 null 或空串时抛出
-
replace
执行模板变量替换。替换语义:
${key}解析为变量值;值为 null 渲染为空串;- 变量缺失(不存在于映射)保留占位符原样;
${key:-default}变量缺失时渲染默认值;$${(escapeChar 连续出现两次)输出字面${;- 未闭合占位符保留原样,空 key
${} 渲染为空。
示例:
StrSubstitutor sub = new StrSubstitutor(); sub.replace("${name} 缺省=${missing:-N/A}", Map.of("name", "sure")); // => "sure 缺省=N/A"- Parameters:
template- 模板文本;为 null 时返回 nullvars- 变量映射;为 null 时视为空映射- Returns:
- 替换结果
-