java替换多个字符,Java一次(或以最有效的方式)替换字符串中的多个不同子字符串...

I need to replace many different sub-string in a string in the most efficient way.

is there another way other then the brute force way of replacing each field using string.replace ?

解决方案

If the string you are operating on is very long, or you are operating on many strings, then it could be worthwhile using a java.util.regex.Matcher (this requires time up-front to compile, so it won't be efficient if your input is very small or your search pattern changes frequently).

Below is a full example, based on a list of tokens taken from a map. (Uses StringUtils from Apache Commons Lang).

Map tokens = new HashMap();

tokens.put("cat", "Garfield");

tokens.put("beverage", "coffee");

String template = "%cat% really needs some %beverage%.";

// Create pattern of the format "%(cat|beverage)%"

String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";

Pattern pattern = Pattern.compile(patternString);

Matcher matcher = pattern.matcher(template);

StringBuffer sb = new StringBuffer();

while(matcher.find()) {

matcher.appendReplacement(sb, tokens.get(matcher.group(1)));

}

matcher.appendTail(sb);

System.out.println(sb.toString());

Once the regular expression is compiled, scanning the input string is generally very quick (although if your regular expression is complex or involves backtracking then you would still need to benchmark in order to confirm this!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值