Java一次(或以最有效的方式)替换字符串中的多个不同子字符串 [英] Java Replacing multiple different substring in a string at once (or in the most efficient way)

查看:68
本文介绍了Java一次(或以最有效的方式)替换字符串中的多个不同子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以最有效的方式替换一个字符串中的许多不同的子字符串.除了使用 string.replace 替换每个字段的蛮力方法之外,还有其他方法吗?

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 ?

推荐答案

如果您操作的字符串很长,或者您操作的字符串很多,那么使用 java.util.regex.Matcher 可能是值得的(这需要预先编译时间,因此如果您的输入非常小或您的搜索模式频繁更改,则效率会很低).

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).

下面是一个完整的例子,基于从地图中提取的令牌列表.(使用来自 Apache Commons Lang 的 StringUtils).

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

Map<String,String> tokens = new HashMap<String,String>();
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!)

这篇关于Java一次(或以最有效的方式)替换字符串中的多个不同子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆