Apache-common StrSubstitutor进行占位符替换

本文介绍了Apache Commons Text库中的StrSubstitutor,它能替代MessageFormat和String.format的功能。通过代码示例展示了如何使用StrSubstitutor进行变量替换,并详细分析了如何定制StrLookup以处理Map中未找到对应值的情况,以及StrSubstitutor的递归替换特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、代码示例

public static void main(String[] args) {
		Map<String, Object> valueMap = Maps.newHashMap();
		valueMap.put("firstName", "你好");
		valueMap.put("secondName", "他好");
		valueMap.put("menuId", "123");
		valueMap.put("templateId", UUIDLong.longUUID());
		String pattern = "/collaboration/collaboration.do?method=newColl&from=bizconfig&firstName={firstName}&secondName={secondName}&menuId={menuId}&templateId={templateId}";
		StrSubstitutor strSubstitutor = new StrSubstitutor(new MapStrLookup(valueMap), "{", "}", StrSubstitutor.DEFAULT_ESCAPE);
		String replace = strSubstitutor.replace(pattern);
		System.out.println(replace);
}

点评:从上例中代码可知道,对于MessageFormat和String.format的应用场景都可以用StrSubstitutor替换使用。

二、StrSubstitutor分析

/**
     * Creates a new instance and initializes it.
     *
     * @param variableResolver  the variable resolver, may be null
     * @param prefix  the prefix for variables, not null
     * @param suffix  the suffix for variables, not null
     * @param escape  the escape character
     * @throws IllegalArgumentException if the prefix or suffix is null
     */
    public StrSubstitutor(StrLookup variableResolver, String prefix, String suffix, char escape) {
        this.setVariableResolver(variableResolver);
        this.setVariablePrefix(prefix);
        this.setVariableSuffix(suffix);
        this.setEscapeChar(escape);
    }

    /**
     * Creates a new instance and initializes it.
     *
     * @param variableResolver  the variable resolver, may be null
     * @param prefixMatcher  the prefix for variables, not null
     * @param suffixMatcher  the suffix for variables, not null
     * @param escape  the escape character
     * @throws IllegalArgumentException if the prefix or suffix is null
     */
    public StrSubstitutor(
            StrLookup variableResolver, StrMatcher prefixMatcher, StrMatcher suffixMatcher, char escape) {
        this.setVariableResolver(variableResolver);
        this.setVariablePrefixMatcher(prefixMatcher);
        this.setVariableSuffixMatcher(suffixMatcher);
        this.setEscapeChar(escape);
    }
2.1 可为StrSubstitutor定制StrLookup,从而可以解决如果在Map中没有找到对应值的解决措施

比如我上例的代码是为了生成URL,如果没有找到Key值的话,URL就会变成:/collaboration/collaboration.do?method=newColl&from=bizconfig&firstName={firstName}&secondName={secondName}&menuId=123&templateId=-6672438965046130710,这种URL结构在浏览器上访问立马就报400了,所以我就定制了StrLookup,如下:

/**
	 * MapStrLookup默认实现,解决如果没有值的时候没有做替换导致URL请求400
	 */
	static class MapStrLookup extends StrLookup {
		private final Map map;
		MapStrLookup(Map map) {
			this.map = map;
		}

		@Override
		public String lookup(String key) {
			if (map == null) {
				return null;
			}
			Object obj = map.get(key);
			if (obj == null) {
				return StringUtils.EMPTY;
			}
			return obj.toString();
		}
	}
2.2 StrSubstitutor实现了递归地替换变量
	public static void main(String[] args) {
		Map<String, Object> valueMap = Maps.newHashMap();
		valueMap.put("firstName", "你好");
		valueMap.put("secondName", "{firstName}");
		valueMap.put("menuId", "123");
		valueMap.put("templateId", UUIDLong.longUUID());
		String pattern = "/collaboration/collaboration.do?method=newColl&from=bizconfig&firstName={firstName}&secondName={secondName}&menuId={menuId}&templateId={templateId}";
		StrSubstitutor strSubstitutor = new StrSubstitutor(new MapStrLookup(valueMap), "{", "}", StrSubstitutor.DEFAULT_ESCAPE);
		String replace = strSubstitutor.replace(pattern);
		System.out.println(replace);
	}

执行结果:

/collaboration/collaboration.do?method=newColl&from=bizconfig&firstName=你好&secondName=你好&menuId=123&templateId=1780653443789639665

三、参考链接

  1. StrSubstitutor
  2. 使用Apache commons-text进行占位符替换
  3. Apache StrSubstitutor使用方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值