我需要以最有效的方式替换字符串中的许多不同子字符串。 除了使用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 = Patternpile(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一次(或以最有效的方式)替换字符串中的多个不同子字符串
发布评论