Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Replacing multiple different substring in a string at once (or in the most efficient way)

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 ?

like image 718
Yossale Avatar asked Aug 25 '09 07:08

Yossale


People also ask

How do I replace multiple substrings in a string?

Replace multiple different substrings There is no method to replace multiple different strings with different ones, but you can apply replace() repeatedly. It just calls replace() in order, so if the first new contains the following old , the first new is also replaced. You need to be careful in order.

Is substring faster than replace?

As expected, the substring is fastest because: It avoids compiling a regular expression.


1 Answers

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

like image 68
Todd Owen Avatar answered Sep 21 '22 17:09

Todd Owen