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

编程入门 行业动态 更新时间:2024-10-18 10:15:11
本文介绍了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 = 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一次(或以最有效的方式)替换字符串中的多个不同子字符串

本文发布于:2023-11-08 20:20:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   多个   最有效   或以   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!